Skip to content

Commit 3eb4e6c

Browse files
committed
Optimize Array methods with SWAP/std::move
Updated Array::shuffle() to use SWAP instead of copying through temporary variables, which makes shuffling simple types around 2x faster, and refcounted object types around 20x faster. Also updated multiple methods that insert into/modify the array to move their validated Variant to avoid an extra copy, speed increase varies depending on type and how much else the methods are doing, usually around 5-10% faster.
1 parent ef1153b commit 3eb4e6c

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed

core/variant/array.cpp

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ void Array::push_back(const Variant &p_value) {
277277
ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
278278
Variant value = p_value;
279279
ERR_FAIL_COND(!_p->typed.validate(value, "push_back"));
280-
_p->array.push_back(value);
280+
_p->array.push_back(std::move(value));
281281
}
282282

283283
void Array::append_array(const Array &p_array) {
@@ -308,14 +308,14 @@ Error Array::insert(int p_pos, const Variant &p_value) {
308308
ERR_FAIL_COND_V_MSG(_p->read_only, ERR_LOCKED, "Array is in read-only state.");
309309
Variant value = p_value;
310310
ERR_FAIL_COND_V(!_p->typed.validate(value, "insert"), ERR_INVALID_PARAMETER);
311-
return _p->array.insert(p_pos, value);
311+
return _p->array.insert(p_pos, std::move(value));
312312
}
313313

314314
void Array::fill(const Variant &p_value) {
315315
ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
316316
Variant value = p_value;
317317
ERR_FAIL_COND(!_p->typed.validate(value, "fill"));
318-
_p->array.fill(value);
318+
_p->array.fill(std::move(value));
319319
}
320320

321321
void Array::erase(const Variant &p_value) {
@@ -485,7 +485,7 @@ void Array::set(int p_idx, const Variant &p_value) {
485485
Variant value = p_value;
486486
ERR_FAIL_COND(!_p->typed.validate(value, "set"));
487487

488-
operator[](p_idx) = value;
488+
_p->array.write[p_idx] = std::move(value);
489489
}
490490

491491
const Variant &Array::get(int p_idx) const {
@@ -703,9 +703,7 @@ void Array::shuffle() {
703703
Variant *data = _p->array.ptrw();
704704
for (int i = n - 1; i >= 1; i--) {
705705
const int j = Math::rand() % (i + 1);
706-
const Variant tmp = data[j];
707-
data[j] = data[i];
708-
data[i] = tmp;
706+
SWAP(data[i], data[j]);
709707
}
710708
}
711709

@@ -732,7 +730,7 @@ void Array::push_front(const Variant &p_value) {
732730
ERR_FAIL_COND_MSG(_p->read_only, "Array is in read-only state.");
733731
Variant value = p_value;
734732
ERR_FAIL_COND(!_p->typed.validate(value, "push_front"));
735-
_p->array.insert(0, value);
733+
_p->array.insert(0, std::move(value));
736734
}
737735

738736
Variant Array::pop_back() {

0 commit comments

Comments
 (0)