Java Best Practices – String performance and Exact String Matching
javacodegeeks.com
javacodegeeks.com
if("botulinum".equals(bacteria))
instead of: if(bacteria.equals("botulinum")) //fetch the name of bacteria from somewhere
String bacteria = getBacteriaName();
if("botulinum".equals(bacteria)) {
//do something
} else {
//do something else
}
Now, if for any reason the getBacteriaName() method failed and gave you a null instead of some string, the code will end up doing whatever it is you want it to do if the bacteria name is other than "botulinum". But this might not be what is really desired. The method failed and this should be taken into consideration. The string bacteria doesn't contain the name of some other bacteria, it's null. The problem here is that, under the circumstances, perhaps the code should have returned 'botulinum' but since the method failed, the program acts as if another bacteria name was fetched instead of throwing an exception. Just something to be careful about.Shame that the article didn't really answer these questions.
for(int i = 0, len = text.length(); i < len; i++) {
// do something
}
avoids the method call to length() in the comparison expression every time. I imagine a lot of you know this, just from time to time I run into someone that balks at what you can do inside of the old-school for headers and how flexible it can be to help make your life inside the loop a hair bit easier. (e.g. init your variable that you want to pull out)As for this article, was excellent. I was surprised at how robust of a test suite it was; fortunately it looks like you only need to get concerned with really robust/complex search algorithms if you are working with large chunks of text and brute-force is surprisingly fast in most shorter cases.
Chalk one up for raw, unsexy CPU power ;)
That said, if you're really in a performance critical section sometimes it doesn't usually hurt to hand-optimize like this, just in case the optimizer craps out for whatever reason and decides to skip optimizing certain sections of code (these reasons can be hard to predict).