2

When bringing externally declared variables into a block...

Using the __block 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?

Gukki5
  • 497
  • 6
  • 22
  • Related: [How does a block capture the variables outside of its enclosing scope?](https://stackoverflow.com/questions/17813870/how-does-a-block-capture-the-variables-outside-of-its-enclosing-scope/17819142#17819142) – jscs Aug 16 '17 at 12:37

2 Answers2

3

The copy won't be costly unless the variable type is a huge struct or huge C++ class.

Even if you declare it as __block, it is initially stored on the stack (like a local variable) but it will get moved to the heap if any block that uses it is copied, and this move will involve a copy of the variable anyway.

newacct
  • 119,665
  • 29
  • 163
  • 224
2

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.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50