From afd59b36cfd64c1f399f47ffa242713d078b3591 Mon Sep 17 00:00:00 2001 From: aaronp64 Date: Mon, 10 Nov 2025 10:27:55 -0500 Subject: [PATCH] Avoid extra copy in Vector/CowData push_back/insert Update push_back/insert methods to move new item into CowData instead of copying --- core/templates/cowdata.h | 12 ++++++------ core/templates/vector.h | 6 +++--- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/core/templates/cowdata.h b/core/templates/cowdata.h index 75d0d346f46..359a6fe269b 100644 --- a/core/templates/cowdata.h +++ b/core/templates/cowdata.h @@ -206,8 +206,8 @@ public: _FORCE_INLINE_ void remove_at(Size p_index); - Error insert(Size p_pos, const T &p_val); - Error push_back(const T &p_val); + Error insert(Size p_pos, T &&p_val); + Error push_back(T &&p_val); _FORCE_INLINE_ operator Span() const { return Span(ptr(), size()); } _FORCE_INLINE_ Span span() const { return operator Span(); } @@ -296,7 +296,7 @@ void CowData::remove_at(Size p_index) { } template -Error CowData::insert(Size p_pos, const T &p_val) { +Error CowData::insert(Size p_pos, T &&p_val) { const Size new_size = size() + 1; ERR_FAIL_INDEX_V(p_pos, new_size, ERR_INVALID_PARAMETER); @@ -326,13 +326,13 @@ Error CowData::insert(Size p_pos, const T &p_val) { } // Create the new element at the given index. - memnew_placement(_ptr + p_pos, T(p_val)); + memnew_placement(_ptr + p_pos, T(std::move(p_val))); return OK; } template -Error CowData::push_back(const T &p_val) { +Error CowData::push_back(T &&p_val) { const Size new_size = size() + 1; if (!_ptr) { @@ -361,7 +361,7 @@ Error CowData::push_back(const T &p_val) { } // Create the new element at the given index. - memnew_placement(_ptr + new_size - 1, T(p_val)); + memnew_placement(_ptr + new_size - 1, T(std::move(p_val))); return OK; } diff --git a/core/templates/vector.h b/core/templates/vector.h index ebca50b77a8..13ef23253cc 100644 --- a/core/templates/vector.h +++ b/core/templates/vector.h @@ -71,8 +71,8 @@ private: public: // Must take a copy instead of a reference (see GH-31736). - _FORCE_INLINE_ bool push_back(T p_elem) { return _cowdata.push_back(p_elem); } - _FORCE_INLINE_ bool append(const T &p_elem) { return push_back(p_elem); } //alias + _FORCE_INLINE_ bool push_back(T p_elem) { return _cowdata.push_back(std::move(p_elem)); } + _FORCE_INLINE_ bool append(T p_elem) { return _cowdata.push_back(std::move(p_elem)); } //alias void fill(T p_elem); void remove_at(Size p_index) { _cowdata.remove_at(p_index); } @@ -133,7 +133,7 @@ public: _FORCE_INLINE_ const T &operator[](Size p_index) const { return _cowdata.get(p_index); } // Must take a copy instead of a reference (see GH-31736). - Error insert(Size p_pos, T p_val) { return _cowdata.insert(p_pos, p_val); } + Error insert(Size p_pos, T p_val) { return _cowdata.insert(p_pos, std::move(p_val)); } Size find(const T &p_val, Size p_from = 0) const { if (p_from < 0) { p_from = size() + p_from;