The Cost of a Closure in C
3 days ago
- #C++
- #closures
- #performance
- Closures are programming constructs that include data alongside instructions, not directly related to their input arguments or return values.
- Closures generalize the concept of functions, allowing them to work with instance data not passed directly, such as variables from surrounding scopes.
- Most modern languages support closures unless targeting low-level programming environments like stack or bytecode languages.
- The article focuses on closures in C and C++, aiming to standardize a solution for ISO C.
- A common problem in C is passing extra data to functions like `qsort`, often solved with static variables, which have limitations like thread safety and shared state issues.
- Four major solutions in C/C++ include: reimplementing functions with userdata pointers, GNU Nested Functions, Apple Blocks, and C++ Lambdas.
- Performance benchmarks show C++ Lambdas (non-type-erased) as the fastest, while GNU Nested Functions and Rosetta Code-style Lambdas perform poorly due to optimization barriers.
- Apple Blocks offer moderate performance but are hindered by ARC overhead and copying behavior.
- The article suggests that a slim, type-erased layer (like `std::function_ref`) could balance usability and performance for C closures.
- Existing extensions like GNU Nested Functions and Apple Blocks have implementation flaws, making them unsuitable for ISO C standardization without improvements.