Skip to content

Instantly share code, notes, and snippets.

@Cananito
Last active October 28, 2016 03:29
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 Cananito/1b4a91e69b568a17ebe27b99eb74b41c to your computer and use it in GitHub Desktop.
Save Cananito/1b4a91e69b568a17ebe27b99eb74b41c to your computer and use it in GitHub Desktop.
import XCTest
class CopyOnWriteWorkaroundTests: XCTestCase {
func testFirst() {
self.measure { //0.272 sec
var dict = ["a":[]]
for i in 0..<10000 {
if dict["a"] != nil {
dict["a"]!.append(i)
} else {
dict["a"] = []
}
}
}
}
func testSecond() {
self.measure { // 0.254 sec
var dict = ["a":[]]
for i in 0..<10000 {
var arr = dict["a"] ?? []
arr.append(i)
dict["a"] = arr
}
}
}
func testCorrect() {
var dict: Dictionary<String, [Int]> = ["a":[]]
for i in 0..<5 {
if dict["a"] != nil {
dict["a"]!.append(i)
} else {
dict["a"] = []
}
}
let arr = dict["a"]!
XCTAssert(arr == [0, 1, 2, 3, 4])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment