Skip to content

Instantly share code, notes, and snippets.

@carlosefonseca
Created June 13, 2014 16:37
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 carlosefonseca/2318c50bf52b55af2287 to your computer and use it in GitHub Desktop.
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
// 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"]]
}
@carlosefonseca
Copy link
Author

Tried some variants of d2["A"] += "A3" but couldn't find one that worked.

@carlosefonseca
Copy link
Author

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