String indexOf Performance

Scott Palmer swpalmer at gmail.com
Fri Jan 27 20:14:06 UTC 2017


On Fri, Jan 27, 2017 at 1:37 PM, Aleksey Shipilev <shade at redhat.com> wrote:
>
> On 01/27/2017 07:22 PM, Scott Palmer wrote:
> > 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
>
> Ah, OK. There's no reason to dive into the performance of this particular
> benchmark. Please isolate the behavior you are seeing with JMH, and possibly see
> the generated code with -prof perfasm (or xperfasm, since you're on Windows).
>
> Thanks,
> -Aleksey
>

JMH results:

Benchmark                              Mode  Cnt      Score     Error  Units
IndexOfBenchmark.StringIndexOfChar    thrpt  200  45387.001 ± 175.235  ops/s
IndexOfBenchmark.StringIndexOfString  thrpt  200  81835.195 ± 157.637  ops/s


My test methods are simple:

    static final String [] paths = new String[1000];
    static {
        for (int i = 0; i < paths.length; i++) {
            paths[i] = ((i & 1) == 0) ? randomName() : randomNameWithSlash();
        }
    }

  @Benchmark
    public static int StringIndexOfChar() {
        int acc = 0;
        for (String s : paths) {
            if (s.indexOf('/') > -1) {
                acc++;
            }
        }
        return acc;
    }

    @Benchmark
    public static int StringIndexOfString() {
        int acc = 0;
        for (String s : paths) {
            if (s.indexOf("/") > -1) {
                acc++;
            }
        }
        return acc;
    }


I'm not set up to run xperfasm.  It appears non-trivial to do.

Regards,

Scott


More information about the jdk9-dev mailing list