Skip to content

Commit

Permalink
[runtime] add array concat optimization (#979)
Browse files Browse the repository at this point in the history
The optimization is applied in case at least one of operands is empty.
In that case it eliminates copy creation and returns a shared array.
  • Loading branch information
apolyakov authored Apr 12, 2024
1 parent e80556b commit 6f2f88d
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
10 changes: 10 additions & 0 deletions runtime/array.inl
Original file line number Diff line number Diff line change
Expand Up @@ -1565,6 +1565,16 @@ void array<T>::merge_with_recursive(const mixed &other) noexcept {

template<class T>
const array<T> array<T>::operator+(const array<T> &other) const {
bool this_empty{this->empty()};
bool other_empty{other.empty()};

// short path in case at least one array is empty
if (this_empty || other_empty) {
if (this_empty && other_empty) { return {}; }
else if (other_empty) { return *this; }
else { return other; }
}

array<T> result(size() + other.size());

if (is_vector()) {
Expand Down
51 changes: 51 additions & 0 deletions tests/phpt/array/032_array_concat.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
@ok
<?php

function test_array_concat_empty() {
/** @var int[] */
$arr = [1, 2, 3];

/** @var int[] */
$empty1 = [];

/** @var int[] */
$empty2 = [];

$tmp1 = $arr + $empty1;
$tmp2 = $empty1 + $arr;
$tmp3 = $empty1 + $empty2;

$arr[0] = -1;
$empty1[0] = -2;
$empty2[0] = -3;
$tmp1[0] = -4;
$tmp2[0] = -5;
$tmp3[0] = -6;

var_dump($arr);
var_dump($empty1);
var_dump($empty2);
var_dump($tmp1);
var_dump($tmp2);
var_dump($tmp3);

// ==========================================================================

$map = ["one" => 1, "two" => 2, "three" => 3];

/** @var int[] */
$empty3 = [];

$tmp4 = $map + $empty3;
$tmp5 = $empty3 + $map;

$map["one"] = -1;
$tmp4["one"] = -2;
$tmp5["one"] = -3;

var_dump($map);
var_dump($tmp4);
var_dump($tmp5);
}

test_array_concat_empty();

0 comments on commit 6f2f88d

Please sign in to comment.