Overview: Optimize what needs optimizing
You can only know what makes your program slow after first getting the program to give correct results, then running it to see if the correct program is slow. When found to be slow, profiling can show what parts of the program are consuming most of the time. A comprehensive but quick-to-run test suite can then ensure that future optimizations don’t change the correctness of your program. In short:
- Get it right.
- Test it’s right.
- Profile if slow.
- Repeat from 2.
Certain optimizations amount to good programming style and so should be learned as you learn the language. An example would be moving the calculation of values that don’t change within a loop, outside of the loop.