StringBuilder vs substring( x )
vs split( x )
vs Regex
Answer Edited : Major Flaws Corrected
After correcting for some fairly major flaws in my benchmarking (as pointed out by Jay Askren in the comments). The StringBuilder
method came out as the fastest by a significant margin (although this assumes that the StringBuilder
objects were pre-created), with substring coming out in second place. split()
came out second to last at 10x slower than the StringBuilder
method.
ArrayList<String> strings = new ArrayList<String>();
ArrayList<StringBuilder> stringBuilders = new ArrayList<StringBuilder>();
for(int i = 0; i < 1000; i++) strings.add("Remove the word remove from String "+i);
for(int i = 0; i < 1000; i++) stringBuilders.add(new StringBuilder(i+" Remove the word remove from String "+i));
Pattern pattern = Pattern.compile("\\w+\\s");
// StringBuilder method
before = System.currentTimeMillis();
for(int i = 0; i < 5000; i++){
for(StringBuilder s : stringBuilders){
s.delete(0, s.indexOf(" ") + 1);
}
}
after = System.currentTimeMillis() - before;
System.out.println("StringBuilder Method Took "+after);
// Substring method
before = System.currentTimeMillis();
for(int i = 0; i < 5000; i++){
for(String s : strings){
String newvalue = s.substring(s.indexOf(" ") + 1);
}
}
after = System.currentTimeMillis() - before;
System.out.println("Substring Method Took "+after);
//Split method
before = System.currentTimeMillis();
for(int i = 0; i < 5000; i++){
for(String s : strings){
String newvalue = s.split(" ", 2)[1];
System.out.print("");
}
}
after = System.currentTimeMillis() - before;
System.out.println("Your Method Took "+after);
// Regex method
before = System.currentTimeMillis();
for(int i = 0; i < 5000; i++){
for(String s : strings){
String newvalue = pattern.matcher(s).replaceFirst("");
}
}
after = System.currentTimeMillis() - before;
System.out.println("Regex Method Took "+after);
I ran the above in random orders, after a warm up, in succession taking averages, increased the number of operations from 5 million to 30 million, and ran each ten times before moving on to the next. Either way the order of fastest to slowest stayed the same. Below is some sample output from the code above;
StringBuilder Method Took 203
Substring Method Took 588
Split Method Took 1833
Regex Method Took 2517
It is worth mentioning that calling split()
with a String
with a length greater than 1 simply uses Regex in its implementation and so there should be no difference between using split()
and a Pattern
object.