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
diff --git a/libutils/binder/VectorImpl.cpp b/libutils/binder/VectorImpl.cpp
index d951b8b..a62664f 100644
--- a/libutils/binder/VectorImpl.cpp
+++ b/libutils/binder/VectorImpl.cpp
@@ -463,7 +463,8 @@
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);