Skip to content

Commit b0a1aad

Browse files
staabmsebastianbergmann
authored andcommitted
Improve performance of TimeEfficientLongestCommonSubsequenceCalculator
1 parent 57a71cc commit b0a1aad

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

src/TimeEfficientLongestCommonSubsequenceCalculator.php

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,24 @@ public function calculate(array $from, array $to): array
3737

3838
for ($i = 1; $i <= $fromLength; $i++) {
3939
for ($j = 1; $j <= $toLength; $j++) {
40-
$o = ($j * $width) + $i;
41-
$matrix[$o] = max(
42-
$matrix[$o - 1],
43-
$matrix[$o - $width],
44-
$from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0
45-
);
40+
$o = ($j * $width) + $i;
41+
42+
// don't use max() to avoid function call overhead
43+
$firstOrLast = $from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0;
44+
45+
if ($matrix[$o - 1] > $matrix[$o - $width]) {
46+
if ($firstOrLast > $matrix[$o - 1]) {
47+
$matrix[$o] = $firstOrLast;
48+
} else {
49+
$matrix[$o] = $matrix[$o - 1];
50+
}
51+
} else {
52+
if ($firstOrLast > $matrix[$o - $width]) {
53+
$matrix[$o] = $firstOrLast;
54+
} else {
55+
$matrix[$o] = $matrix[$o - $width];
56+
}
57+
}
4658
}
4759
}
4860

0 commit comments

Comments
 (0)