提高 Java 中字符串连接的性能 [英] Improving performance of string concatenation in Java

查看:38
本文介绍了提高 Java 中字符串连接的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
java 字符串连接

如何提高这段代码的性能:

How to Improve performance of this chunk of code :

public static String concatStrings(Vector strings) {
    String returnValue = "";

    Iterator iter = strings.iterator();
    while( iter.hasNext() ) {
        returnValue += (String)iter.next();
    }

    return returnValue;
}

推荐答案

您可能会考虑使用 StringBuilder,而不是对单个字符串执行 +=.字符串在 Java 中是不可变的,这意味着一旦创建了 String 对象,就无法修改它.在循环中对字符串使用 += 将导致创建许多单独的 String 实例,这可能会产生性能问题.StringBuilder 可以连接字符串而无需创建新实例,这可能会节省一些时间,具体取决于具体场景.

You might look at using StringBuilder, rather than doing += with the individual strings. Strings are immutable in Java, which means that once you create a String object, you cannot modify it. Using += on strings in a loop will result in the creation of many separate String instances, which may create performance problems. StringBuilder can concatenate Strings without having to create new instances, which may save some time, depending on the exact scenario.

这篇关于提高 Java 中字符串连接的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆