Skip to content

Instantly share code, notes, and snippets.

@xavipedrals
Created November 28, 2018 16:14
Show Gist options
  • Save xavipedrals/5d1493c53d26f2297826b834ba7fd657 to your computer and use it in GitHub Desktop.
Save xavipedrals/5d1493c53d26f2297826b834ba7fd657 to your computer and use it in GitHub Desktop.
import XCTest
class ArrayVSSetTest: XCTestCase {
//Creation times are practically the same (keeping in mind a set is created from an array)
func testSetCreationPerformance() {
let array = [Int](1...10000)
self.measure {
for _ in 0...100 {
_ = Set(array)
}
}
}
func testArrayCreationPerformance() {
self.measure {
for _ in 0...100 {
_ = [Int](1...10000)
}
}
}
//Creation times decreases if array has repeated values
func testSetCreationWithRepetitionsPerformance() {
let array = Array(repeating: 3, count: 10000)
self.measure {
for _ in 0...100 {
_ = Set(array)
}
}
}
func testArrayCreationPerformance() {
self.measure {
for _ in 0...100 {
_ = [Int](1...10000)
}
}
}
//Adding an array performs x10 times better than a set
func testAddingToSet() {
var set = Set<Int>()
self.measure {
for i in 0...1000 {
set.insert(i)
}
}
}
func testAddingToArray() {
var array = [Int]()
self.measure {
for i in 0...1000 {
array.append(i)
}
}
}
//In searching a set is increadibly superior, no discussion here
func testSearchInSet() {
let array = [Int](1...10000)
let set = Set(array)
self.measure {
for i in 0...1000 {
_ = set.contains(i)
}
}
}
func testSearchinInArray() {
let array = [Int](1...10000)
self.measure {
for i in 0...1000 {
_ = array.first(where: { $0 == i })
}
}
}
//In deleting Set is around 7x faster than the array in this case
func testDeleteInSet() {
let array = [Int](1...10000)
var set = Set(array)
self.measure {
for i in 0...500 {
_ = set.remove(i)
}
}
}
//Funny thing, if trying to delete 1000 first values it crashes (not enough memory?)
func testDeleteInArray() {
var array = [Int](1...10000)
self.measure {
for i in 0...500 {
_ = array.remove(at: i)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment