Skip to content

Instantly share code, notes, and snippets.

@Sorix
Last active July 5, 2019 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sorix/7660cd2635f874db62f129328e5987e8 to your computer and use it in GitHub Desktop.
Save Sorix/7660cd2635f874db62f129328e5987e8 to your computer and use it in GitHub Desktop.
Array performance test for safe and normal get
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()
@Sorix
Copy link
Author

Sorix commented Jul 5, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment