java还原字符串_java基础入门-还原字符串的拼接的过程

平常我们很多时候都会使用字符串的拼接,但是为什么使用“+”号就是比stringbuilder慢,而且慢很多?

实验

package com.ray.teststring;

/**

* 对比拼接字符串的两种方式

*

* @author ray

* @since 2015-04-19

* @version 1.0

*

*/

public class StringJoint {

/**

* 使用+拼接

*/

public void stringJointWithPlus() {

String str = "";

for (int i = 0; i < 60000; i++) {

str += "a";

}

}

/**

* 使用stringbuilder拼接

*/

public void stringJointWithStringBuilder() {

StringBuilder sb = new StringBuilder();

for (int i = 0; i < 60000; i++) {

sb.append("a");

}

}

public static void main(String[] args) {

StringJoint stringJoint = new StringJoint();

long beginTime = System.currentTimeMillis();

stringJoint.stringJointWithPlus();

long firstTime = System.currentTimeMillis();

System.out.println(firstTime - beginTime);// 6813

long beginTime2 = System.currentTimeMillis();

stringJoint.stringJointWithStringBuilder();

long secondTime = System.currentTimeMillis();

System.out.println(secondTime - beginTime2);// 16

}

}

下面我们先输出+号操作里面的东西

package com.ray.teststring;

/**

* 对比拼接字符串的两种方式

*

* @author ray

* @since 2015-04-19

* @version 1.0

*

*/

public class StringJoint {

/**

* 使用+拼接

*/

public void stringJointWithPlus() {

String str = "";

for (int i = 0; i < 60000; i++) {

String temp=str;

System.out.println(temp.equals(str));

str += "a";

System.out.println(temp.equals(str));

}

}

/**

* 使用stringbuilder拼接

*/

public void stringJointWithStringBuilder() {

StringBuilder sb = new StringBuilder();

for (int i = 0; i < 60000; i++) {

sb.append("a");

}

}

public static void main(String[] args) {

StringJoint stringJoint = new StringJoint();

long beginTime = System.currentTimeMillis();

stringJoint.stringJointWithPlus();

long firstTime = System.currentTimeMillis();

System.out.println(firstTime - beginTime);// 6813

long beginTime2 = System.currentTimeMillis();

stringJoint.stringJointWithStringBuilder();

long secondTime = System.currentTimeMillis();

System.out.println(secondTime - beginTime2);// 16

}

}

输出结果:

true

false

true

false

true

false

。。。

从结果上面来看,里面两个对象一直都是交错的不相同

下面我们来还原一下+号的操作:

str += "a";等价于

StringBuilder sb = new StringBuilder();sb.append("a");这两句的执行,所以在+的同时不断的new新的对象,所以导致性能低下

版权声明:本文为博主原创文章,未经博主允许不得转载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值