java - 关于字符串连接行为

标签 java string stringbuilder string-pool

我明白,鉴于字符串的不变性,类似

String a="";
for(int i=0;i++<9;)
    a+=i;

效率非常低,因为最初一个字符串被实例化并放入字符串池,然后使用a+=i创建一个新字符串(0 在第一个循环中),由 a 引用,而前一个现在有资格进行垃圾回收。这种情况发生了九次。

更好的方法是使用 StringBuilder:

StringBuilder a=new StringBuilder("");
for(int i=0;i++<9;)
    a.append(i);

但是当我用 关键字?

String a=new String("");
for(int i=0;i++<9;)
    a+=i;

我知道在这种情况下 a 不会被驻留(它不在字符串池中),但它仍然是不可变的吗? a+=i 指令此时做了什么?该行为是否与我的第一个示例相同?

最佳答案

只有 String literals 或调用 intern() 方法的 Strings 被放入 String水池。串联不会自动插入 String,因此您的示例在字符串池方面将是相同的。

String abc = new String("abc"); //"abc" is put on the pool
abc += "def"; //"def" is put on the pool, but "abcdef" is not
String xyz = "abcdefghi".substring(0, 6).intern(); //"abcdef" is now added to the pool and returned by the intern() function
String xyz = "test"; //test is put on the pool
xyz += "ing"; //ing is put on the pool, but "testing" is not

并对此进行扩展,请注意 String 构造函数不会自动实习(或实习)字符串。使用字符串文字(代码中引号中的字符串)是导致字符串位于字符串池中的原因。

String abc = "abc"; //"abc" is in the pool
String def = "def"; //"def" is in the pool
String str1 = new String(abc + def); //"abcdef" is not in the pool yet
String str2 = new String("abcdef"); //"abcdef" is on the pool now

另请注意,String 复制构造函数几乎从不使用,因为无论如何字符串都是不可变的。

有关更多信息,请阅读答案 here , here , 和 here .

关于java - 关于字符串连接行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30575709/

相关文章:

java - map 按值排序

java - eclipse android 通过使用 HTTP 将 java 值传递给 php

java - 比较 Java 和 Jython 类型时的奇怪行为

c# - 带自定义格式化程序的 String.Format

vb.net - 由于内存中的 StringBuilder 实例过大,服务器停止

java - 在 COMPAS 中定义的任务中找不到文件

C++ multimap<int, vector<string>> 内存分配问题

c# - .NET/C# - 将 char[] 转换为字符串

java - 如何防止Java将XML文件中的 "&"改为 "&amp;"

vb.net - 将VB StringBuilder设置为空字符串的合适方法是什么?