Java的String与StringBuffer、StringBuilder的性能比较


1.先看下测试代码

测试代码如下:
[java] view plain copy

    package com.gbicc.thread;  
      
    public class StringTest {  
        private void funBuffer() {  
            String tempstr = "abcdefghijklmnopqrstuvwxyz";  
            int times = 1500000;  
            long lstart2 = System.currentTimeMillis();  
            StringBuffer sb = new StringBuffer();  
            for (int i = 0; i < times; i++) {  
                sb.append(tempstr);  
            }  
            long lend2 = System.currentTimeMillis();  
            long time2 = (lend2 - lstart2);  
            System.out.println(time2);  
        }  
        private void funBuilder() {  
            String tempstr = "abcdefghijklmnopqrstuvwxyz";  
            int times = 1500000;  
            long lstart2 = System.currentTimeMillis();  
            StringBuilder sb = new StringBuilder();  
            for (int i = 0; i < times; i++) {  
                sb.append(tempstr);  
            }  
            long lend2 = System.currentTimeMillis();  
            long time2 = (lend2 - lstart2);  
            System.out.println(time2);  
        }  
      
        private void funStr() {  
            String tempstr = "abcdefghijklmnopqrstuvwxyz";  
            int times = 100;  
            long lstart1 = System.currentTimeMillis();  
            String str = "";  
            for (int i = 0; i < times; i++) {  
                str += tempstr;  
            }  
            long lend1 = System.currentTimeMillis();  
            long time = (lend1 - lstart1);  
            System.out.println(time);  
        }  
      
        /** 
         * @param args 
         */  
        public static void main(String[] args) {  
            StringTest test = new StringTest();  
            test.funBuilder();  
            test.funBuffer();  
            test.funStr();  
        }  
      
    }  

代码说明:代码里有3个函数,一个是测试String的,一个是测试StringBuffer的,一个是测试StringBuilder的,功能就是让24个英文字母相加。

测试的机器配置:


2.看下测试结果:


时间单位:毫秒
次数 	String花费时间 	StringBuffer花费时间 	StringBuilder花费时间
1000 	47 	0~1 	0~1
5000 	1187 	2 	1
10000 	5634 	2 	1
12000 	8801 	3 	3
15000 	16347 	3 	3
18000 	27202 	4 	4
20000 	35911 	4 	4
50000 	...... 	12 	12
100000 	....... 	31 	30


由此可见,当需要对字符串做修改的时候,如果改动频繁,次数太大,用StringBuffer是不二的选择。

但是,当次数操作1000000次时,OutOfMemoryError了。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值