Last active
July 5, 2019 21:31
-
-
Save Sorix/7660cd2635f874db62f129328e5987e8 to your computer and use it in GitHub Desktop.
Array performance test for safe and normal get
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import XCTest | |
extension Collection where Indices.Iterator.Element == Index { | |
subscript(safe index: Index) -> Iterator.Element? { | |
return indices.contains(index) ? self[index] : nil | |
} | |
} | |
class PerfomanceTester: XCTestCase { | |
let measureIterations = 100_000 | |
let array: [String] = { | |
var array = [String]() | |
for _ in 1...10_000 { | |
array.append("test") | |
} | |
return array | |
}() | |
func testNormal() { | |
measure { | |
for _ in 1...measureIterations { | |
let _ = array[10] | |
} | |
} | |
} | |
func testSafe() { | |
measure { | |
for _ in 1...measureIterations { | |
let _ = array[safe: 10] | |
} | |
} | |
} | |
} | |
PerfomanceTester.defaultTestSuite.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the tweet https://twitter.com/uvasily/status/1147255208629755910