From f4f432801ad40551f286e0de23c139795c2f8c2e Mon Sep 17 00:00:00 2001 From: "Philipp A. Hartmann" Date: Mon, 1 Sep 2014 08:57:21 +0200 Subject: [PATCH] GenericValue: reduce growth factor for array/object reallocations As mentioned by @kosta-github in http://git.io/0gkYSg, the currently used growth factor of 2 is suboptimal for memory performance. An extensive discussion can be found at [1]. This patch reduces the array/object capacity growth factor to 1.5, as many C++ implementations have chosen to use. In order to avoid floating-point arithmetics for computing the new capacity, I did not add any customization parameter for the factor and used a shift+add instead. [1] https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md --- include/rapidjson/document.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/rapidjson/document.h b/include/rapidjson/document.h index ec7f8a6..44a492b 100644 --- a/include/rapidjson/document.h +++ b/include/rapidjson/document.h @@ -885,7 +885,7 @@ public: } else { SizeType oldCapacity = o.capacity; - o.capacity *= 2; + o.capacity += (oldCapacity >> 1); // grow by factor 1.5 o.members = reinterpret_cast(allocator.Realloc(o.members, oldCapacity * sizeof(Member), o.capacity * sizeof(Member))); } } @@ -1130,7 +1130,7 @@ int z = a[0u].GetInt(); // This works too. GenericValue& PushBack(GenericValue& value, Allocator& allocator) { RAPIDJSON_ASSERT(IsArray()); if (data_.a.size >= data_.a.capacity) - Reserve(data_.a.capacity == 0 ? kDefaultArrayCapacity : data_.a.capacity * 2, allocator); + Reserve(data_.a.capacity == 0 ? kDefaultArrayCapacity : (data_.a.capacity + (data_.a.capacity >> 1)), allocator); data_.a.elements[data_.a.size++].RawAssign(value); return *this; }