字符串函数的使用,肯定是使用的非常频繁的。对于计算机来说,对字符串的处理远远没有对二进制的处理性能快。
但是如果单纯的对比使用字符串,性能也是有区别的。接下来,我会对字符串使用的几种方法进行对比,寻找出一种更优的字符串 处理方法。
在Java语言中。String对象是一种常用的数据类型。但不是基本数据类型。String对象可以算是对Char对象的进一步封装。
我们最常使用的字符串函数,包含:subString Split indexOf等等。
接下来,对几种例子做一下对比:
1、字符串的拼接
对于新手程序员,常使用的写法:
String str="hello ";
str+="world!";
System.out.println("str="+str); //打印结果:str=hello world!
有经验的程序员,常用写法:
StringBuilder str=new StringBuilder();
str.append("hello ")
.append("world!");
System.out.println("str="+str.toString()); //打印结果:hello world!
这两种写法的效率,几乎所有的Java程序员心里都有答案了吧。这里就不再花篇幅写了。这篇文章主要说分割查找的优化:
2、字符串分割查找
String orgStr=null;
StringBuilder sb=new StringBuilder();
for(int i =0 ; i < 1000; i ++){
sb.append(i);
sb.append(",");
}
orgStr=sb.toString();
第一种方式,使用split:
for( int i =0 ; i < 1000 ; i ++){
orgStr.split(",");
}
第二种方式,使用StringTokenizer分割
StringTokenizer st=new StringTokenizer();
for (int i = 0; i < 1000; i ++) {
while(st.hasMoreTokens()){
st.nextToken();
}
st=new StringTokenizer(orgStr,",");
}
第三种方式,自己动手完成分割
String tmp=orgStr;
for (int i=0; i<1000; i++) {
while(true){
String splitStr=null;
int j=tmp.indexOf(","); //找分隔符的位置
if(j<0) break; //没有分隔符存在,break
splitStr=tmp.substring(0,j); //找到分隔符,截取子字符串
tmp=tmp.substring(j+1); //剩下需要处理的字符串
}
tmp=orgStr;
}
分析结果:
split()方法功能虽然强大,但是效率最差;StringTokenizer性能由于split()方法,因此,在能够给使用StringTokenizer的模块中,就没有必要使用split();而完全由自己实现的分割算法性能最好,但相对来说,代码的可读性和系统的可维护性最差,只有在系统性能称为主要矛盾的时候才推荐使用该方法。