1. 程式人生 > >String的substring、split, StringTokenizer 擷取字串效能比較

String的substring、split, StringTokenizer 擷取字串效能比較

package com.huawei.jvm.decorater;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class MainTest {


public static void main(String ... args) throws Exception{
MainTest tt = new MainTest();
//定義字串
StringBuilder str= new StringBuilder();
//初始化資料
for (int i=0;i<10000;i++){
str.append("fffffff,");
}
String splStr = str.toString();
//做500次迴圈
int forNumber=500;
//ArrayList list = tt.mySplit(str, ",");
long d1 = System.currentTimeMillis();
for(int i=0;i<forNumber;i++){
List list = tt.mySplit(splStr, ",");
//一次迴圈結束,,重新賦值
splStr = str.toString();
}
System.out.println("mySplit :"+( System.currentTimeMillis()-d1)+"MS");
long d2 = System.currentTimeMillis();
for(int i=0;i<forNumber;i++){
String [] arr = splStr.split(",");
//一次迴圈結束,,重新賦值
splStr = str.toString();
}
System.out.println("plit :"+( System.currentTimeMillis()-d2)+"MS");
long d3 = System.currentTimeMillis();
for(int i=0;i<forNumber;i++){
ArrayList<String> list = new ArrayList<String>();
StringTokenizer st= new StringTokenizer(splStr,",");
while(st.hasMoreElements()){
list.add(st.nextElement().toString());
}
//一次迴圈結束,,重新賦值
splStr = str.toString();
}
System.out.println("StringTokenizer :"+( System.currentTimeMillis()-d3)+"MS");
}

private List<String> mySplit(String str,String limt){
ArrayList<String> list = new ArrayList<String>();
list.ensureCapacity(100);
String newStr=null;
int index = str.indexOf(limt);
while(index>=0){
//newStr = new String( str.substring(0,index));
newStr = str.substring(0,index);
list.add(newStr);
str = str.substring(index+1);
index = str.indexOf(limt);
}
//System.out.println(list.size());
return list;

}

}