|
|
|
Back to newsletter 039 contents
Which way should I write this piece of code to be faster, using feature X or feature Y?
I get a lot of questions like this. I've even written an article or two explaining the performance difference for some types of features, such as this one on the difference between i++ and ++i or this one on the costs of using exceptions in different ways. These are interesting in a pretty low-level kind of way, and occasionally such information can come in useful.
But I can also understand one of my colleagues' response to that "i++ vs. ++i" article. He basically said "get a life". And for basic performance tuning, I pretty much agree with him. The real response to almost all questions like this is to code according to best practices, making your code as readable and maintainable as possible first of all. If you have a couple of alternative ways to code something, don't start thinking about the alternative performance probabilities. Use the more readable option.
Then profile the code using valid and representative test cases to find where the real bottlenecks are, and fix those bottlenecks to be faster. Sure, occasionally the bottleneck will turn out to be where you were asking about one of those alternative features. But most of those alternative features that you could have asked about will not be located in the real bottlenecks. Which means that your code will be that much more readable in most places. And honestly, everyone will be happier in the long run if your code is more readable. Perl programmers find that out pretty quickly.
So the full answer is: Write beautiful code; then profile that beautiful code and make little bits of it uglier but faster. Don't worry too much about performance while you are writing that beautiful code.
The JavaPerformanceTuning.com team
Back to newsletter 039 contents