public void ensureCapacity(int minimumCapacity) {
if (minimumCapacity > value.length) {
expandCapacity(minimumCapacity);
}
}
void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}
NOTE: value.length is the capacity of the StringBuffer, not the length.
It has nothing to do with a null string because minimum capacity is 16.
What I think is, the memory allocations cost so much time, and if we are calling ensureCapacity() frequently with increasing minimumCapacity , (capacity +1)*2 will allocate a bit more memory and may reduce further allocations and save some time.
lets consider initial capacity as 16,
only with doubling 16 , 32 , 64 , 128 , 256 , 512 , 1024 , 2048 , so on...
with double +2 16 , 34 , 70 , 142 , 286 , 574 , 1150 , 2302 , so on...
Thus the memory will gradually keeping increasing every time and may decrease the no of allocations of memory.
int newCapacity = (value.length + 1) * 2;
Won't it be sufficient with just(value.length) * 2;
? That's what I'm curious about. – Bangweulu(value.length + 1) * 2
. I mean is it used as it is in somewhere ? – Histrionismint newCapacity = value.length * 2 + 2;
– Histrionismint newCapacity = (value.length + 1) * 2
actually meant; Add an additional space, and double it down. So that makes sense, since the capacity is filled up, just add ONE additional space, and then double the new length. – Appendage