From 6f7bb5920edf8a7f21cea0dd484040b65bfacdde Mon Sep 17 00:00:00 2001 From: Danny van der Sluijs Date: Fri, 5 May 2023 19:24:41 +0200 Subject: [PATCH] perf: Backport v5 performance improvements onto v4.0.4 (3461e3f) --- ...ientLongestCommonSubsequenceCalculator.php | 7 +++++- ...ientLongestCommonSubsequenceCalculator.php | 24 ++++++++++++++----- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/src/MemoryEfficientLongestCommonSubsequenceCalculator.php b/src/MemoryEfficientLongestCommonSubsequenceCalculator.php index 0b626eaf..489113b6 100644 --- a/src/MemoryEfficientLongestCommonSubsequenceCalculator.php +++ b/src/MemoryEfficientLongestCommonSubsequenceCalculator.php @@ -78,7 +78,12 @@ private function length(array $from, array $to): array if ($from[$i] === $to[$j]) { $current[$j + 1] = $prev[$j] + 1; } else { - $current[$j + 1] = max($current[$j], $prev[$j + 1]); + // don't use max() to avoid function call overhead + if ($current[$j] > $prev[$j + 1]) { + $current[$j + 1] = $current[$j]; + } else { + $current[$j + 1] = $prev[$j + 1]; + } } } } diff --git a/src/TimeEfficientLongestCommonSubsequenceCalculator.php b/src/TimeEfficientLongestCommonSubsequenceCalculator.php index fd19cac7..4e8d951d 100644 --- a/src/TimeEfficientLongestCommonSubsequenceCalculator.php +++ b/src/TimeEfficientLongestCommonSubsequenceCalculator.php @@ -37,12 +37,24 @@ public function calculate(array $from, array $to): array for ($i = 1; $i <= $fromLength; ++$i) { for ($j = 1; $j <= $toLength; ++$j) { - $o = ($j * $width) + $i; - $matrix[$o] = max( - $matrix[$o - 1], - $matrix[$o - $width], - $from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0 - ); + $o = ($j * $width) + $i; + + // don't use max() to avoid function call overhead + $firstOrLast = $from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0; + + if ($matrix[$o - 1] > $matrix[$o - $width]) { + if ($firstOrLast > $matrix[$o - 1]) { + $matrix[$o] = $firstOrLast; + } else { + $matrix[$o] = $matrix[$o - 1]; + } + } else { + if ($firstOrLast > $matrix[$o - $width]) { + $matrix[$o] = $firstOrLast; + } else { + $matrix[$o] = $matrix[$o - $width]; + } + } } }