I think String.indexOf(char)
is a little faster than
String.indexOf(String)
when using single character & single String(ex, 'x' & "x")
To make sure my guessing, I wrote easy test code like below.
public static void main(String[] args) {
IndexOfTest test = new IndexOfTest(Integer.parseInt(args[0]));
test.run();
}
public IndexOfTest(int loop) {
this.loop = loop;
}
public void run() {
long start, end;
start = System.currentTimeMillis();
for(int i = 0 ; i < loop ; i++) {
alphabet.indexOf("x");
}
end = System.currentTimeMillis();
System.out.println("indexOf(String) : " + (end - start) + "ms");
start = System.currentTimeMillis();
for(int i = 0 ; i < loop ; i++) {
alphabet.indexOf('x');
}
end = System.currentTimeMillis();
System.out.println("indexOf(char) : " + (end - start) + "ms");
}
alphabet
is String variable that has "abcd...xyzABCD...XYZ".
from this code, I got result table like this...
loop 10^3 10^4 10^5 10^6 10^7
String 1 7 8 9 9
char 1 2 5 10 64
String.indexOf(String)
looks like converge to 9ms, however String.indexOf(char)
increases exponentially.
I'm very confused. Is there any optimization for using String
in this case?
Or how I figure out this result?
Update
I ran jmh with below two benchmark method. Each method calls a indexOf method.
@State(Scope.Thread)
public class MyBenchmark {
private String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
@Benchmark
public void indexOfString() {
alphabet.indexOf("x");
}
@Benchmark
public void indexOfChar() {
alphabet.indexOf('x');
}
}
result:
Benchmark Mode Cnt Score Error Units
MyBenchmark.indexOfChar thrpt 30 142106399.525 ± 51360.808 ops/s
MyBenchmark.indexOfString thrpt 30 2178872840.575 ± 864573.421 ops/s
This result also show indexOf(String)
is faster..
I think that it is time to think about hidden optimization
Any idea?