String - StringBuffer - StringBuilder 效率对比

作者:流沙 分类: JAVA 发布于:2016-6-24 17:03 ė505次浏览 60条评论

测试程序:


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);
	}
}

本文出自 流沙,转载时请注明出处及相应链接。

发表评论

电子邮件地址不会被公开。必填项已用*标注


Ɣ回顶部