3 ms·
If people wrote the most optimal code the first time, we wouldn't need optimizing compilers, and all the undefined behavior that optimization passes necessarily
by kmeisthax 2y ago
If people wrote the most optimal code the first time, we wouldn't need optimizing compilers, and all the undefined behavior that optimization passes necessarily bring along. The whole point of the example is to be poorly written in a way that the compiler "obviously" should be able to fix, but can't.
A less obvious example would be...
- A struct, A, which has an init_from_file method that deserializes data from a Read: R
- Another struct, B, which has its own init_from_file, and a variable number of A as one of its fields. B::init_from_file needs to deserialize by calling A::init_from_file in a tight loop.
This example is the same as the first, except now we've disguised the inefficiency with separation of concerns. A compiler can inline A::init_from_file into B::init_from_file to yield the same code as in the example.
- auggierose 2y agoSo you are saying that the buffer would be allocated in the program in A::init_from_file? And the compiler would be able to optimise that away by allocating the buffer outside the loop? If the compiler actually does that, that would be a good example. As long as I don't have to be careful to write my code in a way that some obscure compiler optimisation understands.