为什么 IntelliJ 要我改变这个?
Why does IntelliJ wants me to change this?
简单的一行代码:
String thing = "Something";
thing += " something else" + " and more.";
IntelliJ IDEA 提供将此行更改为其他 4 种方式来实现相同的结果:
String.format()
StringBuilder.append()
java.text.MessageFormat.format()
Replace += with =
为什么? += 有什么问题?谁能解释一下?谢谢
一般情况下,结果是不一样的。 +
运算符分配中间字符串,这需要额外的内存。
String thing = "Something";
thing += " something else" + " and more."; // two allocations: to compute string inside expression ```" something else" + " and more."```` and to execute ```+=```
通过使用 StringBuilder
,您无需分配中间结果,例如需要更少的内存。
在您使用短线且没有循环的情况下,预计不会有实际的性能提升。但是,对于循环,您会收到 O(N^2)
的复杂性。请检查 this answer 和解释示例。
我假设你指的是这个:
这实际上并不是对您的代码的修复 "problem",如铅笔图标所示。对代码问题的修复用灯泡标识,例如不使用 thing
:
的值
铅笔就是"here's a shortcut to change your code, so you don't have to change it manually"。将 a += b
更改为 a = a + b
通常没有那么多工作,但其他事情,例如将 for-each 循环更改为常规 for 循环,是。
如果您突然想起需要数组的索引来做某事,这可能会很有用。
简单的一行代码:
String thing = "Something";
thing += " something else" + " and more.";
IntelliJ IDEA 提供将此行更改为其他 4 种方式来实现相同的结果:
String.format()
StringBuilder.append()
java.text.MessageFormat.format()
Replace += with =
为什么? += 有什么问题?谁能解释一下?谢谢
一般情况下,结果是不一样的。 +
运算符分配中间字符串,这需要额外的内存。
String thing = "Something";
thing += " something else" + " and more."; // two allocations: to compute string inside expression ```" something else" + " and more."```` and to execute ```+=```
通过使用 StringBuilder
,您无需分配中间结果,例如需要更少的内存。
在您使用短线且没有循环的情况下,预计不会有实际的性能提升。但是,对于循环,您会收到 O(N^2)
的复杂性。请检查 this answer 和解释示例。
我假设你指的是这个:
这实际上并不是对您的代码的修复 "problem",如铅笔图标所示。对代码问题的修复用灯泡标识,例如不使用 thing
:
铅笔就是"here's a shortcut to change your code, so you don't have to change it manually"。将 a += b
更改为 a = a + b
通常没有那么多工作,但其他事情,例如将 for-each 循环更改为常规 for 循环,是。
如果您突然想起需要数组的索引来做某事,这可能会很有用。