There are two methods:
private static void normalSplit(String base){
base.split("\\.");
}
private static final Pattern p = Pattern.compile("\\.");
private static void patternSplit(String base){
//use the static field above
p.split(base);
}
And I test them like this in the main method:
public static void main(String[] args) throws Exception{
long start = System.currentTimeMillis();
String longstr = "a.b.c.d.e.f.g.h.i.j";//use any long string you like
for(int i=0;i<300000;i++){
normalSplit(longstr);//switch to patternSplit to see the difference
}
System.out.println((System.currentTimeMillis()-start)/1000.0);
}
Intuitively,I think as String.split
will eventually call Pattern.compile.split
(after a lot of extra work) to do the real thing. I can construct the Pattern object in advance (it is thread safe) and speed up the splitting.
But the fact is, using the pre-constructed Pattern is much slower than calling String.split
directly. I tried a 50-character-long string on them (using MyEclipse), the direct call consumes only half the time of using pre-constructed Pattern object.
Please can someone tell me why this happens ?
Pattern.compile(regex).split(this, limit)
, but only if the string to split by is more than a single character. At least in OpenJDK7, See here, line 2312.