java - Pattern.split slower than String.split -
there 2 methods:
private static void normalsplit(string base){ base.split("\\."); } private static final pattern p = pattern.compile("\\."); private static void patternsplit(string base){ //use static field above p.split(base); }
and test them in 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 long string for(int i=0;i<300000;i++){ normalsplit(longstr);//switch patternsplit see difference } system.out.println((system.currenttimemillis()-start)/1000.0); }
intuitively,i think string.split
call pattern.compile.split
(after lot of work) real thing. can construct pattern object in advance (it thread safe) , speed splitting.
but fact is, using pre-constructed pattern much slower calling string.split
directly. tried 50-character-long string on them (using myeclipse), direct call consumes half time of using pre-constructed pattern object.
please can tell me why happens ?
this may depend on actual implementation of java. i'm using openjdk 7, , here, string.split
indeed invoke pattern.compile(regex).split(this, limit)
, only if string split by, regex
, more single character.
see here source code, line 2312.
public string[] split(string regex, int limit) { /* fastpath if regex (1)one-char string , character not 1 of regex's meta characters ".$|()[{^?*+\\", or (2)two-char string , first char backslash , second not ascii digit or ascii letter. */ char ch = 0; if (((regex.count == 1 && // bunch of other checks , lots of low-level code return list.sublist(0, resultsize).toarray(result); } return pattern.compile(regex).split(this, limit); }
as splitting "\\."
, using "fast path". is, if using openjdk.
Comments
Post a Comment