java - StringBuilder.append() 是否应该始终优先于串联?

标签 java concatenation stringbuilder

我有一些这样的代码:

StringBuilder rgba = new StringBuilder();  
for (...){
....
rgba.append(value + ", ");
}

IntelliJ 向我显示以下警告:

string concatenation as argument to 'stringbuilder.append()' call

来自here , here和其他来源,我知道串联实际上创建了一个新的 String 对象,并且否定了使用 StringBuilder 的全部意义。
所以 IntelliJ 建议我使用

rgba.append(value);
rgba.append(", ");  

而不是

rgba.append(value + ", ");  

但这真的会更好吗?
这段代码会不会更清晰一些?
这会使执行速度更快吗?

最佳答案

根据 IntelliJ 推理:

Reports String concatenation used as the argument to StringBuffer.append(), StringBuilder.append() or Appendable.append(). Such calls may profitably be turned into chained append calls on the existing StringBuffer/Builder/Appendable, saving the cost of an extra StringBuffer/Builder allocation. This inspection ignores compile time evaluated String concatenations, which when converted to chained append calls would only worsen performance.

所以,我想说:加油!

关于java - StringBuilder.append() 是否应该始终优先于串联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66529296/

相关文章:

java - 使用 DividerItemDecoration 隐藏 recyclerview 中的一些项目分隔线

mysql - 为什么这个错误 : Illegal mix of collations (utf8_general_ci, IMPLICIT) and (utf8_bin,NONE) for operation '=' , ON THIS QUERY?

JavaScript 用退格键连接字符串

android - 寻找一种 GC 友好的方式来频繁替换子字符串

java - Java 基准测试(比较两个类)

java - 从 geotools Filter 对象恢复或重建 CQL 字符串

java - opengl/lwjgl 的透明度问题

java - 从txt文件中读取

c++ - 为什么在定义宏 ## 操作时有 2 层间接寻址

java - 空指针异常字符串生成器