Skip to content

Commit dead87b

Browse files
kaja47ondrejmirtes
authored andcommitted
Speed up CombinationHelper
This change swaps loops to reduce number of intermediate arrays allocated and flips direction in which results are constructed to eliminate explicit append loop. For 3 arrays with 10 elements each this leads to 5x speedup.
1 parent 0f28194 commit dead87b

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed

src/Internal/CombinationsHelper.php

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
namespace PHPStan\Internal;
44

5-
use function array_shift;
5+
use function array_pop;
66

77
final class CombinationsHelper
88
{
@@ -19,14 +19,12 @@ public static function combinations(array $arrays): iterable
1919
return;
2020
}
2121

22-
$head = array_shift($arrays);
22+
$last = array_pop($arrays);
2323

24-
foreach ($head as $elem) {
25-
foreach (self::combinations($arrays) as $combination) {
26-
$comb = [$elem];
27-
foreach ($combination as $c) {
28-
$comb[] = $c;
29-
}
24+
foreach (self::combinations($arrays) as $combination) {
25+
foreach ($last as $elem) {
26+
$comb = $combination;
27+
$comb[] = $elem;
3028
yield $comb;
3129
}
3230
}

0 commit comments

Comments
 (0)