Home > Articles > Programming > C/C++

  • Print
  • + Share This
From the author of Should You Use Closures?

Should You Use Closures?

Adding closures to C was an interesting idea, but not necessarily a good one. Apple's blocks, in particular, are being used in a lot of places because they allow a lot of complexity to be hidden. Unfortunately, this technique removes one of the advantages of using C as a language: the fact that it's easy to see the cost of every operation. For example, consider this snippet:

int a = 0;
__block int b = 0;
a++;
b++;

The last two lines both refer to on-stack variables, and both perform an increment operation. However, they don't have the same cost. Accesses to the block-qualified variable must go via an indirection pointer, so they require two memory accesses (although, hopefully, both are in the same cache line—but still not helping pipelining). The _Block_copy() function also makes reasoning about performance difficult. The cost of calling it depends on whether the block is on the stack or on the heap already, which you may not know, and on the kinds of variables that are bound to it.

Nested functions and C++ lambdas are simpler. They just allow you to pass a transient function down the stack, or provide some slightly cleaner syntax for private functions in the case of C++ lambdas. They have a cost similar to that of normal functions, but remove some of the big advantages of closures.

  • + Share This
  • 🔖 Save To Your Account