Re:Zero Cost Abstractions
by Manishearth on Wednesday November 30, 2016 @07:06PM
(#13075869)
All of the optimizations were done by llvm, so nothing stopping this from working in C++ with closures or C with functions annotated for inlining.
With C the lack of generics means that writing composable iterators is hard, though.
At least it's hard to write composable iterators that don't circumvent the type system completely.
Since ranges are not yet standard, the "equivalent" abstractions would look to be std::algorithms, but those are not zero-cost as they are not iterator adaptors, but consumers. This is extremely inefficient.
However, Boost offers iterator adapters, which although weaker than true iterator adapters (which C++ calls ranges), those will suffice in this case.
As for std::algorithms not being zero-cost. I have seen cases were std::foreach was noticably faster or much slower. I have seen it in benchmarks and it seems largely to be a quality of implementation issue.
Good implementations can cheat and use knowledge my code shouldn't have about parts of the underlying system and bad ones do extra useless crap.
Benchmarking and profiling seem to be the only real way to gain confidence in your results reliably.
That said, I'd expect something similar to happen with a well-written C program. Would equivalent abstractions in C++1{1,4,7} be "costly"?