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.
Support PMD, get the book - PMD Applied!
now you have one for
sb.append('c')
and
str.indexOf('c')
and possible more with a single character.
Wouldn't it be possible to make a general rule for all places where you use a single string character and make it to a char?
I think its always better to that.. or did i overlook some cases where it's not possible?
Posted by: simonsays | January 13, 2006 at 03:51 PM
nevermind.. it ofcourse have to accept a char.
but what about concatenation with a single letter or is there a rule for that already?
str+'c'
Posted by: simonsays | January 13, 2006 at 03:59 PM
Interesting rule Tom!
Is there the same performance benefit (and if so, does your new rule catch) this:
int iSearchPos = 5;
String string = ....;
string.indexOf('c', iSearchPos);
(searching from a given position)
Posted by: Allan Caplan | January 13, 2006 at 04:16 PM
Hi Allan -
Yup, it catches that case... although I hadn't thought about it when coding that rule up, thanks for the pointer! I've added a test case for it...
Yours,
Tom
Posted by: tomcopeland | January 13, 2006 at 05:04 PM
Hi simonsays -
Hm, I suppose we could combine these two rules... hm. I'm not sure. I kind of feel like it might be trying to do too much, since AppendCharacterWithChar deals with StringBuffers and UseIndexOfChar deals with strings.
Yours,
Tom
Posted by: tomcopeland | January 13, 2006 at 05:06 PM
Looking at the code for String.indexOf(String) may be misleading. A good JVM will treat the method as an intrinsic.
Incidentally, String.concat may be faster than using the String + operator. Particularly from 1.5.
Posted by: Tom Hawtin | January 13, 2006 at 07:36 PM
Tom -
Hm, good point. I've been using JDK 1.4 for benchmarking... perhaps I should give it a whirl on something newer.
Great stuff on your blog, by the way; thanks for posting those. I like the builder suggestions here especially:
http://jroller.com/page/tackline?entry=static_creation_methods
Tom
Posted by: tomcopeland | January 13, 2006 at 09:14 PM