测试程序:
package com.gyarmy.string; import java.util.ArrayList; import org.junit.Test; /* * StringBuffer 可变的字符序列 * */ public class TestStringBuffer { /* * StringBuilder 5.0以后加入, 线程不安全, 效率高于StringBuffer * */ @Test public void test2(){ //效率对比 //String,StringBuffer, StringBuilder String str=""; long startTime = 0L; long endTime = 0L; StringBuffer buffer = new StringBuffer(""); StringBuilder builder = new StringBuilder(""); startTime = System.currentTimeMillis(); for(int i=0;i<20000;i++) { buffer.append(String.valueOf(i)); } endTime = System.currentTimeMillis(); System.out.println("StringBuffer的时间为:"+(endTime-startTime)); startTime = System.currentTimeMillis(); for(int i=0;i<20000;i++) { builder.append(String.valueOf(i)); } endTime = System.currentTimeMillis(); System.out.println("StringBuilder的时间为:"+(endTime-startTime)); startTime = System.currentTimeMillis(); for(int i=0;i<20000;i++) { //builder.append(String.valueOf(i)); str = str+String.valueOf(i); } endTime = System.currentTimeMillis(); System.out.println("String的时间为:"+(endTime-startTime)); } @Test public void test1(){ StringBuffer sb = new StringBuffer(); System.out.println(sb.length()); sb.append("abcd").append("国家").append("123"); System.out.println(sb.length()); System.out.println(sb); ArrayList list = new ArrayList(); sb.insert(1, "www.youku.com"); System.out.println(sb); sb.reverse(); System.out.println(sb); } }
0则评论给“String - StringBuffer - StringBuilder 效率对比”