String indexOf Performance

Scott Palmer swpalmer at gmail.com
Fri Jan 27 17:20:00 UTC 2017


I’m not sure if this is the right list, please redirect me if it is not.

I was looking into optimizing some code and was surprised to find that String.indexOf(char) was significantly slower than String.indexOf(String) for a single character search.  (E.g. I’m looking for a slash / in a path.)
The seems counter intuitive, but on Java 8 I saw String.indexOf(char) was about 30% slower than String.indexOf(String).  Then I tested on Java 9 and found the performance difference was actually greater because indesOf(String) was now faster, but indexOf(char) was about the same speed.  I presume this is related to the new compact strings.

Am I missing something or should I not expect indexOf(char) to be as fast or faster than indexOf(String) for a string of length 1?

Regards,

Scott


More information about the jdk9-dev mailing list