【问题标题】:Java - StringBuilder vs Concatenation of strings [duplicate]Java - StringBuilder 与字符串的串联[重复]
【发布时间】:2019-03-09 23:12:00
【问题描述】:

问题很简单,避免不占用内存使用什么更好?例如,假设我们有一个String s = "Test",我们想将1 添加到它上面,这样它就变成了Test1。我们都知道s获得了一个内存位置,如果我们使用StringBuilderTest1将获得一个新的内存地址或者它会留在s的位置,如果我们使用concat呢?

【问题讨论】:

标签: java stringbuilder string-concatenation


【解决方案1】:

单行连接在底层被优化并转换为StringBuilder。记忆明智是同样的事情,但手动连接更简洁。

// the two declarations are basically the same
// JVM will optimize this to StringBuilder
String test = "test";
test += "test";

StringBuilder test = new StringBuilder();
test.append("test");

另一方面,如果你不做琐碎的连接,你会更好StringBuilder

// this is worse, JVM won't be able to optimize
String test = "";
for(int i = 0; i < 100; i ++) {
    test += "test"; 
} 

// this is better
StringBuilder builder = new StringBuilder();
for(int i = 0; i < 100; i ++) {
    builder.append("test"); 
} 
猜你喜欢
  • 1970-01-01
  • 2010-09-09
  • 2014-02-19
  • 2010-10-29
  • 2015-12-23
  • 2019-05-21
  • 2015-06-21
  • 2014-11-05
相关资源
最近更新 更多