Skip to content

Commit c460b12

Browse files
authored
Improve performance of TimeEfficientLongestCommonSubsequenceCalculator
1 parent 57a71cc commit c460b12

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

src/TimeEfficientLongestCommonSubsequenceCalculator.php

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,22 @@ public function calculate(array $from, array $to): array
3838
for ($i = 1; $i <= $fromLength; $i++) {
3939
for ($j = 1; $j <= $toLength; $j++) {
4040
$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-
);
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+
if ($matrix[$o - 1] > $matrix[$o - $width]) {
45+
if ($firstOrLast > $matrix[$o - 1]) {
46+
$matrix[$o] = $firstOrLast;
47+
} else {
48+
$matrix[$o] = $matrix[$o - 1];
49+
}
50+
} else {
51+
if ($firstOrLast > $matrix[$o - $width]) {
52+
$matrix[$o] = $firstOrLast;
53+
} else {
54+
$matrix[$o] = $matrix[$o - $width];
55+
}
56+
}
4657
}
4758
}
4859

0 commit comments

Comments
 (0)