i was wondering why a List<String> for each loop is slower than a split for each on a StringBuilder
This is my code:
package nl.testing.startingpoint;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String args[]) {
NumberFormat formatter = new DecimalFormat("#0.00000");
List<String> a = new ArrayList<String>();
StringBuffer b = new StringBuffer();
for (int i = 0;i <= 10000; i++)
{
a.add("String:" + i);
b.append("String:" + i + " ");
}
long startTime = System.currentTimeMillis();
for (String aInA : a)
{
System.out.println(aInA);
}
long endTime = System.currentTimeMillis();
long startTimeB = System.currentTimeMillis();
for (String part : b.toString().split(" ")) {
System.out.println(part);
}
long endTimeB = System.currentTimeMillis();
System.out.println("Execution time from StringBuilder is " + formatter.format((endTimeB - startTimeB) / 1000d) + " seconds");
System.out.println("Execution time List is " + formatter.format((endTime - startTime) / 1000d) + " seconds");
}
}
The result is:
- Execution time from StringBuilder is 0,03300 seconds
- Execution time List is 0,06000 seconds
I would expect the StringBuilder to be slower because of the b.toString().split(" ")).
Can anyone explain this to me?
Aucun commentaire:
Enregistrer un commentaire