What's the cost of capturing variables in a closure?

In terms of memory and run time, is there cost to capturing variables for a closure? If there is a huge amount of variables in the context, would it be beneficial to explicitly specifying [capture list]?

But I just read that capture list makes copy, not reference to the original variable. I'm kind of confused now. So implicitly capture is totally different from explicitly capture with capture list...hmmmm

A closure will only capture variables you reference inside of it, there is no cost for a variable outside of the closure that isn't used in the closure. What you read is correct, explicitly capturing will copy. This means that this:

func printAndQuadruple(_ x: Int) -> Int { print(x); return x * 4 }
var a = 3
var b = 4
var c = 5
let closure = { [b = printAndQuadruple(b), c] in
	print("Closure: \(a) \(b) \(c)")
}
a *= 2
b *= 2
c *= 2
print("Outside: \(a) \(b) \(c)")
closure()

will print:

4
Outside: 6 8 10
Closure: 6 16 5

because the a inside and outside of the closure are the same (captured by reference) while the b and c are separate. Any computation that happens in the capture list is done at capture time and is only available to the closure.

1 Like