Created
June 13, 2014 16:37
-
-
Save carlosefonseca/2318c50bf52b55af2287 to your computer and use it in GitHub Desktop.
Demonstration of a difference in Swift's Arrays when compared to NS[Mutable]Arrays
This file contains hidden or 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
// Playground - noun: a place where people can play | |
import UIKit | |
var d1 = Dictionary<String, NSMutableArray>() | |
var d2 = Dictionary<String, String[]>() | |
d1["A"] = NSMutableArray(object: "A1") | |
d1 // ["A": ["A1"]] | |
d2["A"] = ["A1"] | |
d2 // ["A": ["A1"]] | |
if var d1A = d1["A"] { | |
d1A.addObject("A2") | |
d1 // ["A": ["A1","A2"]] | |
// NSMutableArray is a class, this always uses the same object | |
} | |
if var d2A = d2["A"] { | |
d2A.append("A2") | |
d2 // ["A": ["A1"]] | |
// Array is a struct, d2A is a copy of d2["A"], changing the lenght of one doens't affect the other. | |
d2["A"] = d2A | |
d2 // ["A": ["A1","A2"]] | |
} |
Yup… With NSMutableArray: 0.017 sec ; with Array: 0.657 sec
func testPerformanceExample() {
var d1 = Dictionary<String, NSMutableArray>()
var d2 = Dictionary<String, String[]>()
d1["A"] = NSMutableArray(object: "A1")
d2["A"] = ["A1"]
let mut = true
self.measureBlock() {
for i in 0..1000 {
if mut {
if var d1A = d1["A"] {
d1A.addObject("A2")
}
} else {
if var d2A = d2["A"] {
d2A.append("A2")
d2["A"] = d2A
}
}
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tried some variants of
d2["A"] += "A3"
but couldn't find one that worked.