java中string链接性能的问题

String链接性能的问题一直是比较基础也是大家比较容易出错和迷惑的问题,在这里就通过几段代码和反编译的代码来详细的介绍一下String链接性能的问题。


第一种情况: 字符串直接赋值常量,然后进行链接。

原始代码

public class test{

	public static void main(String[] args){

		String s = "hello";
		String t = "world";
		String r = "!!";
		String str = s + t + r;
	}


}

反编译之后的代码

public class test
{

    public test()
    {
    }

    public static void main(String args[])
    {
        String s = "hello";
        String s1 = "world";
        String s2 = "!!";
        String s3 = (new StringBuilder()).append(s).append(s1).append(s2).toString();
    }
}


显而易见,字符串连接时是创建了一个StringBuilder,然后进行append操作,这样的好处众所周知:不需要创建过多String的对象(String不可变性),因此效率出众,而且StringBuilder非同步,所以比StringBuffer效率更高。



第二种情况:String对象通过new得到

原始代码

public class test{

	public static void main(String[] args){

		String s = new String("Hello");
		String t = new String("world");
		String r = new String("!!");
		String str = s + t + r;
	}


}


反编译后的代码:

public class test
{

    public test()
    {
    }

    public static void main(String args[])
    {
        String s = new String("Hello");
        String s1 = new String("world");
        String s2 = new String("!!");
        String s3 = (new StringBuilder()).append(s).append(s1).append(s2).toString();
    }
}

这和第一种反编译出来的代码一致,所以从此看出,这样写效率也是极高的,那么什么情况下会出现字符串链接低效的情况呢?看下面第三种情况:

原始代码

public class test{

	public static void main(String[] args){

		String str = new String("Hello ");
		String temp = new String("world ");
		for(int i = 0; i < 100; i++){
			str = str + temp ;		
		}
	}


}

反编译后的代码
public class test
{

    public test()
    {
    }

    public static void main(String args[])
    {
        String s = new String("Hello ");
        String s1 = new String("world ");
        for(int i = 0; i < 100; i++)
            s = (new StringBuilder()).append(s).append(s1).toString();

    }
}
创建了100次StringBuilder这样效率必定也是用String链接一样,所以效率不高

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值