Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason that a compiler would not treat every variable as a __block variable?

What are the performance gains of a compiler (specifically compilers that Xcode uses) not treating every variable as a __block variable? I'd imagine there has to be something, I doubt that during the conception of __block variables it was decided that

 __block SelfClass * blockSelf = self;

is nice and convenient syntax.

like image 225
Eric L Avatar asked Oct 10 '22 14:10

Eric L


1 Answers

The goal of blocks was to make it as automatic and transparent as possible to use blocks with minimal syntax and have them "just work".

Non-__block variables, as the default, are much more in line with the notion of "closures" that blocks represent. A block snapshots the state of all variables referenced within the block at the moment execution passes over the block declaration. This encompasses both copying of memory/state and retaining any Objective-C object references captured in the block.

__block effectively breaks the encapsulation of state within the block. Very useful, but requires manual management of object references on the part of the programmer.

I.e. non-__block variables "just work" more often the __block variables and, thus, the default behavior was to gravitate to "just works".

In practice, the cost of capturing the state within a block is typically minimal. Measurable impact on app performance is typically rare and often indicates an architectural problem of a more profound nature.


If by:

 __block SelfClass * blockSelf = self;

Are you are referring to the cross-product of Blocks and ARC? Yes, that is a bit unfortunate. But the compiler is also warning about a very real issue that you need to be aware of. However, a cleaner workaround would be obviously preferable.

like image 148
bbum Avatar answered Oct 12 '22 03:10

bbum