通过 __block 与不通过 __block 捕获块中的外部变量的性能差异
Performance Differences Capturing External Variables in Blocks via __block vs Not
将外部声明的变量引入块时...
使用 __block
指令通过引用捕获变量...
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.
没有变量被值捕获...
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.
我听说使用__block效率较低,但这怎么可能呢?您不会总是避免昂贵的副本吗?
Won't you always avoid a costly copy?
不,这并不昂贵,因为只复制了 变量。变量是对对象的引用,因此通常是单个机器字。
引用的对象本身未被复制。
除非变量类型是一个巨大的结构或巨大的 C++ class。
,否则副本不会很昂贵
即使您将它声明为 __block
,它最初存储在堆栈中(就像一个局部变量)但是如果任何使用它的块被复制,它就会被移动到堆中,并且这个移动无论如何都会涉及变量的副本。
将外部声明的变量引入块时...
使用 __block
指令通过引用捕获变量...
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.
没有变量被值捕获...
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.
我听说使用__block效率较低,但这怎么可能呢?您不会总是避免昂贵的副本吗?
Won't you always avoid a costly copy?
不,这并不昂贵,因为只复制了 变量。变量是对对象的引用,因此通常是单个机器字。
引用的对象本身未被复制。
除非变量类型是一个巨大的结构或巨大的 C++ class。
,否则副本不会很昂贵即使您将它声明为 __block
,它最初存储在堆栈中(就像一个局部变量)但是如果任何使用它的块被复制,它就会被移动到堆中,并且这个移动无论如何都会涉及变量的副本。