目前,当 javac 遇到字符串连接时,它会将代码转换为使用 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的容量就是这个数组的长度。一旦数组溢出,就会分配一个新的(更长的)数组并将内容传输到其中。这使得容量上升。
关于java - 字符串连接所需的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42665003/