I'd like to see (good) examples of optimizations performed by compilers (static and JIT). Why?
- To learn what we don't have to optimize ourselves (often leading to better code)
- To be amazed
There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.
Someone once tried to examine optimizers in C code. They ran this code through various C compilers with different levels of optimization:
First the compiler noticed that
The loop is empty, so we can remove that, too:
A classical example of removing unused code.
|show 3 more comments|
When I wrote the compiler for my implementation of ECMAScript I noticed that I could not perform recursion to a depth that was greater than 3000 calls. To me this was unacceptable so after a bit of experimentation I came up with the idea of replacing the return value with the arguments that were passed recursively. With this in place recursion became a viable option when writing code for my implementation.
I don't believe that you would ever see this technique used in a professional context. Given the current code a strong relationship is implied
Here is a proper example of tail-call optimization:
Reflected CIL as C#
Notice how the compiler is simply reusing the same stack frame in a while loop. This is very similar to what I implemented but without the unnecessary friendliness between the compiler and the run-time.