先上一个各个方法运行的效率对比图哈~
再来看看代码
package a.demo; import java.util.*; import android.app.Activity; import android.os.Bundle; public class S extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String str = "zkw"; StringBuffer buffer = new StringBuffer(); // 准备好字符串,总共有1000个“zkw”,以“,”相隔 for (int i = 0; i < 1000; i++) { buffer.append(str).append(","); } str = buffer.toString(); //String.split() splitTime(str); //List+indexOf() listTime(str); //String[]+indexof() arrayTime(str); //StringTokenizer tokenizer(str); } private void splitTime(String str) { long curTime = System.currentTimeMillis(); String[] array = null; for (int m = 0; m < 100; m++) { array = str.split(","); } //printArray(array); System.out.println("String.split用时 : " + (System.currentTimeMillis() - curTime)); } private void listTime(String str) { long curTime = System.currentTimeMillis(); String[] array = null; for (int n = 0; n < 100; n++) { ArrayList<String> arrayList = new ArrayList<String>(); int index = 0, offset = 0; while ((index = str.indexOf(",", index + 1)) != -1) { arrayList.add(str.substring(offset, index)); offset = index + 1; } array = arrayList.toArray(new String[0]); } //printArray(array); System.out.println("List+indexOf()用时 : " + (System.currentTimeMillis() - curTime)); } private void arrayTime(String str) { long curTime = System.currentTimeMillis(); String[] array = new String[1001]; for (int n = 0; n < 100; n++) { int index = 0, offset = 0; int i = 0; while ((index = str.indexOf(",", index + 1)) != -1) { array[i] = str.substring(offset, index); offset = index + 1; i++; } array[i] = str.substring(offset); } //printArray(array); System.out.println("String[]+indexOf()用时 : " + (System.currentTimeMillis() - curTime)); } private void tokenizer(String str) { long curTime = System.currentTimeMillis(); String[] array = null; for (int m = 0; m < 100; m++) { StringTokenizer token = new StringTokenizer(str, ","); array = new String[token.countTokens()]; int i = 0; while (token.hasMoreTokens()) { array[i++] = token.nextToken(); } } //printArray(array); System.out.println("StringTokener用时 : " + (System.currentTimeMillis() - curTime)); } /* * 检验每个array数组是否相等 * 仅仅是打印 */ private void printArray(String[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i]); } System.out.println(""); } }
中间两个是自己简单实现的算法,如果专门设计个算法,速度肯定更快!
PS:以前用Python的时候对split()印象挺好的,到了JAVA上发现很少有人用,今天测试才发现是有原因的。
PS2:这个测试仅仅在android平台上有效,在PC上还是split()比StringTokenizer稍微快点,仅仅是稍微,而且还是没有自己实现的算法快...