From e0ec952bae15d296006de86b80782551c144afa4 Mon Sep 17 00:00:00 2001 From: Shai Barack Date: Mon, 7 Oct 2024 15:25:28 +0000 Subject: [PATCH] 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 --- libutils/binder/VectorImpl.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libutils/binder/VectorImpl.cpp b/libutils/binder/VectorImpl.cpp index d951b8bbb..a62664f7b 100644 --- a/libutils/binder/VectorImpl.cpp +++ b/libutils/binder/VectorImpl.cpp @@ -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);