String indexOf Performance

Scott Palmer swpalmer at gmail.com
Fri Jan 27 18:22:59 UTC 2017


On Fri, Jan 27, 2017 at 12:47 PM, Aleksey Shipilev <shade at redhat.com> wrote:

> On 01/27/2017 06:37 PM, Andrew Haley wrote:
> > On 27/01/17 17:20, Scott Palmer wrote:
> >> 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?
> >
> > What hardware?  The hardware matters because intrinsics use SSE 4.2.
> >
> > And how long were the strings?
>
> Better yet, just show your benchmark :)
>
> -Aleksey
>

I'm running on an Intel Core i7 950.  Windows 10.

With my test I generated 1000 strings of various lengths, around 6 to 32
characters.  Every other string had a '/' somewhere in it.

Then I looped through the array to count how many times I found a '/'.
Testing three ways, contains(String), indexOf(char) > -1, and
indexOf(String) > -1.

I looped through those 100,000 times.  I should do a proper JMH benchmark,
but for now here's a link to the code:

  http://pastebin.com/dWcf7rQJ

Regards,

Scott


More information about the jdk9-dev mailing list