Consider this code:
The code is saying "loop 2^63 times, assigning 1 to the variable foo each time".
This is what a compiler could optimize it to:
Today's compilers are smart and getting smarter. Computer scientists (real scientists, not hacks like me writing tips) continue to put the best code optimizations into the compilers themselves, including using statistical analysis to know when, for example, it would be faster to inline a method, and when it would spoil the performance of the JIT. That modern compilers can perform this kind of analysis and still finish a build quicker than their predecessors is quite amazing.
In the long run the best optimizations you can make to your code are to follow the philosophy of the language, because this is what the compiler will be designed to optimize. If the language favors a functional or declarative style of programming, then avoid trying to do everything in an imperative fashion. Likewise, if the language clearly wants you to write explicit loops and conditionals, then don't try to force a functional style on top of it.
Your relationship with the compiler is similar to the relationship web sites have with search engines, another area where "optimization" is a hot topic and black arts are pretended to be used. And just like with compilers, many search engine optimization tricks of the 90s will backfire and hurt you if you tried to use them today.
Gratitude to the Coding Reddit crowd for feedback and corrections.