Which of the following is better:
Sample1:
var x: Int = 0
for _ in 1...5 {
someList.append( Foobar(someClosure: { println("X = \(x)") }))
}
Sample2:
var x: Int = 0
var c: ()->() = { println("X = \(x)") }
for _ in 1...5 {
someList.append( Foobar(someClosure: c))
}
- If I think of closures as reference types, then sample2 would be best since I'm reusing the same object (reduce memory allocation, reuse objects).
- If I think of closures as value types, then it really doesn't matter. I would have to trust the compiler to recognized that the closures are the same and that it knows to use the same closure (similarly to what would happen if I used the same literal string within my code in multiple locations). Choosing one over the other would be considered "premature optimization".
Edit:
Is there a fundamental difference between both samples (aside from writing style)?