我在研究Apache的StringUtils.join
方法的实现时,无意中发现了一条我认为是为了性能的行,但我不明白为什么他们会以这种方式使用这些特定的值。
以下是实现:
public static String join(Object[] array, String separator, int startIndex, int endIndex) {
if (array == null) {
return null;
}
if (separator == null) {
separator = EMPTY;
}
// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
// (Assuming that all Strings are roughly equally long)
int noOfItems = (endIndex - startIndex);
if (noOfItems <= 0) {
return EMPTY;
}
StringBuilder buf = new StringBuilder(noOfItems * 16); // THE QUESTION'S ABOUT THIS LINE
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
我的问题是关于StringBuilder buf = new StringBuilder(noOfItems * 16);
线的:
StringBuilder
一个初始容量目标性能,所以在构建字符串时需要更少的调整。我的问题是:这些调整大小的操作实际上对性能有多大影响?这种策略在速度上真的提高了效率吗?(因为就空间而言,如果分配的空间超过必要,甚至可能为负数)16
?为什么他们会假设数组中的每个String
都有16个字符长?这个猜测有什么用?发布于 2016-05-17 17:31:52
16
是对带有分隔符的字符串的预期平均大小的略微高估(大概是基于经验/统计)。
预先分配足够的空间来保存整个结果,避免在执行过程中用更大的(双倍大小)数组替换支持数组,并复制元素(这是O(n)操作)。
如果在大多数情况下避免了替换操作,即使过高估计,分配一个更大的数组也是值得的。
发布于 2016-05-16 12:50:15
真的..。这并不是你在问题中所说的唯一硬编码的16
。
如果你再查一遍这个定义。你会发现这样的东西。
bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length())
+ separator.length());
//16 will only assigned if Object array at position StartIndex contains null.
StringBuffer buf = new StringBuffer(bufSize); //if null then default memory allocation for String Buffer will be 16 only.
在这里,StringBuffer
将调用构造函数,该构造函数将作为
new StringBuffer(int Capacity);
Constructs a string buffer with no characters in it and the specified initial capacity.
如果Object包含at索引startIndex
的元素,那么默认的内存分配将是该Object
的length
。
谢谢。
发布于 2020-05-16 20:29:27
嗯..。StringUtils.join
在大数组中生成OutOfMemory Exception
.;您知道这种情况。
https://stackoverflow.com/questions/37253848
复制相似问题