字符串连接所需的解决方法

Workaround around needed for string concatenation

目前,当 javac 遇到 String 连接时,它会将代码转换为使用 StringBuilder。例如:

String a = String.valueOf(System.currentTimeMillis());
    String b = String.valueOf(System.currentTimeMillis());
    String c = String.valueOf(System.currentTimeMillis());
    String d = a + b + c + "_IND";

变成类似

的东西
String d = new StringBuilder().append(a).append(b).append(c).append("_IND");

由于未明确调整 StringBuilder 的大小,因此使用默认大小,并且当默认大小太小时通常会导致在运行时调用 expandCapacity。

在分析应用程序时,我们看到了许多这样的操作,例如为各种 HashMap 构建键,为 JSF 中的每个元素构建唯一键等 这会导致额外的内存使用。

有没有更好的方法来减少这种情况。

In cases where you are trying to insert bigger strings in the StringBuilder it is always wiseable to interpret the size of the big string and initialize your StringBuider with the somewhat more than estimated size as its default capacity.

推导一个经验公式来得出 StringBuilder 的初始化能力,以便您控制低估和高估大小的成本。

因为StringBuilder以char数组的形式存储正在构建的字符串。 StringBuilder 的容量就是这个数组的长度。一旦数组溢出,就会分配一个新的(更长的)数组并将内容传输给它。这使得容量上升。