Avoid unnecessary allocation in VectorImpl

When shrinking a vector, we might reallocate the buffer
if the current capacity is too large, or we might reuse
the existing buffer.
Never reallocate the buffer if the current capacity is
already at the minimum (i.e. we won't actually shrink by
reallocating).

Bug: 370649413
Change-Id: I665037ed2a8621a82f2b58bcc834934de0761f34
Flag: EXEMPT bugfix
Tested: see b/370649413#comment6
This commit is contained in:
Shai Barack 2024-10-07 15:25:28 +00:00
parent 7cc50a8c29
commit e0ec952bae

View file

@ -463,7 +463,8 @@ void VectorImpl::_shrink(size_t where, size_t amount)
size_t new_size;
LOG_ALWAYS_FATAL_IF(__builtin_sub_overflow(mCount, amount, &new_size));
if (new_size < (capacity() / 2)) {
const size_t prev_capacity = capacity();
if (new_size < (prev_capacity / 2) && prev_capacity > kMinVectorCapacity) {
// NOTE: (new_size * 2) is safe because capacity didn't overflow and
// new_size < (capacity / 2)).
const size_t new_capacity = max(kMinVectorCapacity, new_size * 2);