Skip to content

Commit c1afe7d

Browse files
committed
Improve CowData::insert performance
Update CowData::insert to call ptrw() before loop, to avoid calling _copy_on_write for each item in the array, as well as repeated index checks in set and get. For larger Vectors/Arrays, this makes inserts around 10x faster for ints, 3x faster for Strings, and 2x faster for Variants. Less of an impact on smaller Vectors/Arrays, as a larger percentage of the time is spent allocating.
1 parent 97b8ad1 commit c1afe7d

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

core/templates/cowdata.h

+8-5
Original file line numberDiff line numberDiff line change
@@ -222,12 +222,15 @@ class CowData {
222222
}
223223

224224
Error insert(Size p_pos, const T &p_val) {
225-
ERR_FAIL_INDEX_V(p_pos, size() + 1, ERR_INVALID_PARAMETER);
226-
resize(size() + 1);
227-
for (Size i = (size() - 1); i > p_pos; i--) {
228-
set(i, get(i - 1));
225+
Size new_size = size() + 1;
226+
ERR_FAIL_INDEX_V(p_pos, new_size, ERR_INVALID_PARAMETER);
227+
Error err = resize(new_size);
228+
ERR_FAIL_COND_V(err, err);
229+
T *p = ptrw();
230+
for (Size i = new_size - 1; i > p_pos; i--) {
231+
p[i] = p[i - 1];
229232
}
230-
set(p_pos, p_val);
233+
p[p_pos] = p_val;
231234

232235
return OK;
233236
}

0 commit comments

Comments
 (0)