Sting中字符串连接:

Sting中字符串连接:

  • 请罗列出来对于字符串而言常见的拼接方法,并且编写用例来推导出他们之间的性能差异?
1.package com.mage.changyonglei;  
1.public class Test {  
2.    public static void main(String[] args) {  
3.        test01();  
4.        test03();  
5.        test02();  
6.       
7.    }  
8.    public static void test01() {  
9.        long start = System.currentTimeMillis();  
10.        StringBuffer sb = new StringBuffer("a");  
11.        for(int i = 0;i<100000;i++) {  
12.            sb.append("c");  
13.        }  
14.        long end = System.currentTimeMillis();  
15.        System.out.println("append:"+(end-start));  
16.    }  
17.      
18.    public static void test02() {  
19.        long start = System.currentTimeMillis();  
20.        String sb = new String("a");  
21.        for(int i = 0;i<100000;i++) {  
22.            sb = sb+"c";  
23.        }  
24.        long end = System.currentTimeMillis();  
25.        System.out.println("+号:"+(end-start));  
26.    }  
27.      
28.    public static void test03() {  
29.        long start = System.currentTimeMillis();  
30.        String sb = new String("a");  
31.        for(int i = 0;i<100000;i++) {  
32.             sb = sb.concat("c");  
33.        }  
34.        long end = System.currentTimeMillis();  
35.        System.out.println("concat:"+(end-start));  
36.    }  
37.      
38.}  

运行结果图:

在这里插入图片描述

总结:

1.字符串常见的拼接有三种方法:“+”号拼接、concat、append

2…append拼接一般在StringBuilder或者StringBuffer中使用,拼接速度是最快的。

3…"+"号拼接如果左右两边拼接的是字面值的话,则加号拼接是最快的。

4.就此题而言拼接效率:append>concat>+

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值