Gukki5 Gukki5 - 1 year ago 54
Objective-C Question

Performance Differences Capturing External Variables in Blocks via __block vs Not

When bringing externally declared variables into a block...

Using the

directive captures a variable by reference...

Variables local to the enclosing lexical scope declared with the __block storage modifier are provided by reference and so are mutable.
Any changes are reflected in the enclosing lexical scope, including any other blocks defined within the same enclosing lexical scope.

Without the variable is captured by value...

Local variables declared within the lexical scope of the block, which behave exactly like local variables in a function.
Each invocation of the block provides a new copy of that variable. These variables can in turn be used as const or by-reference variables in blocks enclosed within the block.

I've heard it said that using the __block is less efficient, but how is this possible? Won't you always avoid a costly copy?

Answer Source

Won't you always avoid a costly copy?

No, this is not costly, because solely the variable is copied. The variable is a reference to an object, therefore typically a single machine word.

The referred object itself is not copied.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download