`
李灵晖-raylee
  • 浏览: 128968 次
博客专栏
Group-logo
从头认识java
浏览量:0
文章分类
社区版块
存档分类
最新评论

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新的对象,所以导致性能低下



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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics