Comment

Comment by bugake

That's not guaranteed. An array or variable could be modified by another thread, meaning that reversing the order of operations could produce a different result. The compiler cannot always assume that such transformations are safe, and that's why the compiler avoids implementing a lot of those optimizations that you expect to be done automagically.

So you cannot expect the compiler to automatically perform every possible optimization. The programmer still needs to understand how the code behaves and write it with performance in mind.

You may be perfectly sure that no other thread modifies the data, but the compiler doesn't know, so it avoids all kind of optimizations.

If you expect the compiler to perform those optimizations automatically, you still have to do things like declare certain variable variables and or function parameters as constant (since the compiler may otherwise have to assume that their values could be modified by side effects/threads, preventing certain optimizations), use specific attributes or annotations on functions, and provide specific compilation flags. That's more complex than simply coding the for loop backwards.

And the worst thing is that frequently the compiler assumes a constant could be modified anyway, and avoids optimizing just in case.

parent bugake 1 day ago

No comments yet

Be the first to share your thoughts.

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton