String str = "abc";
StringBuffer buffer = new StringBuffer();
// prepare the string
for (int i = 0; i < 10000; i ++){
buffer.append(str).append(",");
}
str = buffer.toString();
// java.util.StringTokenizer
long curTime = System.currentTimeMillis();
for (int m = 0; m < 1000; m ++){
StringTokenizer token = new StringTokenizer(str, ",");
String[] array2 = new String[token.countTokens()];
int i = 0;
while (token.hasMoreTokens()){
array2[i++] = token.nextToken();
}
}
System.out.println("java.util.StringTokener : " + (System.currentTimeMillis() - curTime));
// String.split()
curTime = System.currentTimeMillis();
for (int m = 0; m < 1000; m ++){
String[] array = str.split(",");
}
System.out.println("String.split : " + (System.currentTimeMillis() - curTime));
curTime = System.currentTimeMillis();
for (int n = 0; n < 1000; n ++){
Vector<String> vector= new Vector<String>();
int index = 0, offset = 0;
while ((index = str.indexOf(",", index + 1)) != -1){
vector.addElement(str.substring(offset, index));
offset = index + 1;
}
String[] array3 = vector.toArray(new String[0]);
}
System.out.println("Vector & indexOf : " + (System.currentTimeMillis() - curTime));
输出----
java.util.StringTokener : 1407
String.split : 2546
Vector & indexOf : 1094
很显眼,使用StringTokenizer比使用Spring.split()提高接近一倍的性能。
而是用indexOf来逐步查找,性能还能进一步提高25%左右。很显然,越接近底层的方法性能越得到满足。
不过,这个只是在于对性能要求高的需求底下才有真正的意义。普通应用,String.split()足以 |