标签:
一、概述
字符串的处理在java中我们经常要用到java提供了三个类来提供对字符串的操作,String,StringBuffer,StringBuilder
String:固定长StringBuffer:不固定长线程安全Stringbuilder:不固定长线程不安全
二、性能PK
1.创建超大字符串。
代码:
public class StringOne { public static void main(String[] args) { String str=""; StringBuffer strb=new StringBuffer(); StringBuilder strbd=new StringBuilder(); long startString=System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { str=str+i; } System.out.println("String add Time:"+(System.currentTimeMillis()-startString)); long startStringBuffer=System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { strb.append(i); } System.out.println("StringBuffer add Time:"+(System.currentTimeMillis()-startStringBuffer)); long startStringBuilder=System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { strbd.append(i); } System.out.println("StringBuilder add Time:"+(System.currentTimeMillis()-startStringBuilder)); } }
效果图:
2.字符串常量的添加操作
代码:
public class StringTwo { public static void main(String[] args) { long startString=System.currentTimeMillis(); for (int i = 0; i < 100000000; i++) { String str="String"+"and"+"String"+"append"; } System.out.println("String Time:"+(System.currentTimeMillis()-startString)); long startStringBuffer=System.currentTimeMillis(); for (int i = 0; i < 100000000; i++) { StringBuffer strb=new StringBuffer(); strb.append("String"); strb.append("and"); strb.append("String"); strb.append("append"); } System.out.println("StringBuffer Time:"+(System.currentTimeMillis()-startStringBuffer)); long startStringBuilder=System.currentTimeMillis(); for (int i = 0; i < 100000000; i++) { StringBuilder strbdr=new StringBuilder(); strbdr.append("String"); strbdr.append("and"); strbdr.append("String"); strbdr.append("append"); } System.out.println("StringBuilder Time:"+(System.currentTimeMillis()-startStringBuilder)); } }
效果图:
三、总结
通过上述的性能对比得出结论在我们构建超大字符串的时候StringBuffer和StringBulder的表现比String的表现要好的很多不是一个数量级的而在字符串常量的添加操作中String的表现比StringBuffer和StringBuilder的表现好,原因就在于在创建String类的比创建StringBuffer和StringBuilder使用的开销小时间短,所以这三个类的用法各有千秋根据我们具体的业务去选择用哪一个类。
Java入门到精通——基础篇String StringBuffer StringBuilder性能PK
标签:
原文地址:http://blog.csdn.net/gwblue/article/details/45919999