Optimization Rules
First off: a warning. Optimized methods can sometimes be much less readable than their unoptimized counterparts. Take, for example, the texture mapping code from , "Texture Mapping and Lighting." The simple, unoptimized code was just a few lines long, but the final optimized version grew to a few pages. Although the code is fast, unfortunately it's also less readable and more difficult to maintain. In past instances, I've optimized a method so much that I've forgotten how it works! Also, hand-optimizing your code can introduce errors, such as rare bugs or different behavior in different situations. In short, optimized code can often become quite a mess. So, when optimizing, consider these ideas:
- Don't optimize! First, attempt to create code that is easier to read, maintain, and modify.
- Optimize only methods that absolutely need it-the 20%.
- When you do optimize a method, it's a good idea to keep the original, unoptimized version in case you need to refer to it later.
- Make test cases to ensure the optimized method behaves the same as the unoptimized method.
- Don't bother optimizing in ways that HotSpot already does for you.
- If you try to optimize something and get zero benefit, undo the optimization.
With this in mind, let's get started on finding that 20%.