Closures in C and C++ have vastly different performance characteristics depending on implementation. Benchmarking the Man-or-Boy test reveals that C++ lambdas without type erasure are fastest, while GNU Nested Functions perform poorly due to executable stack requirements that prevent optimization. Apple Blocks perform moderately well but are limited by ARC overhead. The article demonstrates that std::function_ref provides good performance with minimal type erasure cost, while std::function and certain lambda capture patterns cause significant slowdowns. Wide function pointers are proposed as an efficient solution for C closures.

38m read timeFrom thephd.dev
Post cover image
Table of contents
“Closures”?The Closure ProblemNot A Big OverviewPurrrrrrrformance :3 !MethodologyThe ResultsThinking It Over

Sort: