Effective Java 51 Beware the performance of string concatenation
2014-04-14 10:47 小郝(Kaibo Hao) 阅读(354) 评论(0) 编辑 收藏 举报Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n. It's an unfortunate consequence of fact that strings are immutable(Item 15).
// Inappropriate use of string concatenation - Performs horribly!
public String statement() {
String result = "";
for (int i = 0; i < numItems(); i++)
result += lineForItem(i); // String concatenation
return result;
}
To achieve acceptable performance, use a StringBuilder in place of a String
public String statement() {
StringBuilder b = new StringBuilder(numItems() * LINE_WIDTH);
for (int i = 0; i < numItems(); i++)
b.append(lineForItem(i));
return b.toString();
}
Summary
Don't use the string concatenation operator to combine more than a few strings unless performance is irrelevant. Use StringBuilder's append method instead. Alternatively, use a character array, or process the strings one at a time instead of combining them.
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。