以前一直以为这种写法

String test = "123"+"345"+"456";

以前认为String + 效率是特别低的,每次都会创建一个新的字符串,应该用StringBuilder.append代替。最近偶然看了下jdk api文档

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.


Java 语言提供对字符串串联符号(”+”)以及将其他对象转换为字符串的特殊支持。字符串串联是通过 StringBuilder(或 StringBuffer)类及其append 方法实现的。字符串转换是通过 toString 方法实现的,该方法由 Object 类定义,并可被 Java 中的所有类继承。有关字符串串联和转换的更多信息,请参阅 Gosling、Joy 和 Steele 合著的 The Java Language Specification

然而我看了一下StringBuildertoString方法

    @Override
    public String toString() {
        // Create a copy, don't share the array
        return new String(value, 0, count);
    }

还是会每次创建一个新的字符串,所以如果这样写

                String test = "";
		for (Integer i : treeSet) {
			test += i;
		}

还是等于

                String test = "";
		for (Integer i : treeSet) {
			test = stringBuilder.append(i).toString();
		}

还是会每次创建一个新的对象。
所以说然并卵,还是用+没问题不要用+=…..

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据