Fast String.indexOf()

13 Jan 2006

Another string optimization PMD rule! If you see code calling String.indexOf() like this:

String str = "hello world";
int location = str.indexOf("w"); // using indexOf(String) with a one character String!

That works, but a faster way is to do:

String str = "hello world"
int location = str.indexOf('w'); // use indexOf(char) instead

I did a bit of benchmarking, and using String.indexOf(char) is about 10-20% faster depending on the String length and the location of the target character within the String. If you're wondering why it's faster, take a peek at the source code for String.indexOf(char) and String.indexOf(String); you'll see the difference just in the amount of code in the implementation. It's a minor optimization, but inside a tight loop, it could make a difference - can't hurt, anyhow!

This new rule is called UseIndexOfChar and it's in the strings ruleset in PMD's CVS repository.