Skip to content

Commit

Permalink
Use LocalVector.reserve internally instead of copying code.
Browse files Browse the repository at this point in the history
On `reserve`, do not allocate more capacity than requested even if the current capacity is not a power of 2.
  • Loading branch information
Ivorforce committed Jan 2, 2025
1 parent 0f95e9f commit b92ea23
Showing 1 changed file with 3 additions and 12 deletions.
15 changes: 3 additions & 12 deletions core/templates/local_vector.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,7 @@ class LocalVector {
}

_FORCE_INLINE_ void push_back(T p_elem) {
if (unlikely(count == capacity)) {
capacity = tight ? (capacity + 1) : MAX((U)1, capacity << 1);
data = (T *)memrealloc(data, capacity * sizeof(T));
CRASH_COND_MSG(!data, "Out of memory");
}

reserve(size() + 1);
if constexpr (!std::is_trivially_constructible_v<T> && !force_trivial) {
memnew_placement(&data[count++], T(p_elem));
} else {
Expand Down Expand Up @@ -138,8 +133,8 @@ class LocalVector {
_FORCE_INLINE_ bool is_empty() const { return count == 0; }
_FORCE_INLINE_ U get_capacity() const { return capacity; }
_FORCE_INLINE_ void reserve(U p_size) {
p_size = tight ? p_size : nearest_power_of_2_templated(p_size);
if (p_size > capacity) {
p_size = tight ? p_size : nearest_power_of_2_templated(p_size);
capacity = p_size;
data = (T *)memrealloc(data, capacity * sizeof(T));
CRASH_COND_MSG(!data, "Out of memory");
Expand All @@ -156,11 +151,7 @@ class LocalVector {
}
count = p_size;
} else if (p_size > count) {
if (unlikely(p_size > capacity)) {
capacity = tight ? p_size : nearest_power_of_2_templated(p_size);
data = (T *)memrealloc(data, capacity * sizeof(T));
CRASH_COND_MSG(!data, "Out of memory");
}
reserve(p_size);
if constexpr (!std::is_trivially_constructible_v<T> && !force_trivial) {
for (U i = count; i < p_size; i++) {
memnew_placement(&data[i], T);
Expand Down

0 comments on commit b92ea23

Please sign in to comment.