Skip to content

Commit

Permalink
diff: simplify LCS_matrix() (#915)
Browse files Browse the repository at this point in the history
* Initialise $x[$i] to new listref [0] in one statement, instead of assigning list element 0 separately
* Calling standard max() function avoids temporary variables when compared items are different
* Write loops in idiomatic form with ranges
* This was intended as a readability change, but I observed that when generating diffs on a large text files the performance is slightly improved

%time perl diff.old -u bc bc.new > /dev/null
real	0m11.003s
...
real	0m10.845s
...
real	0m10.965s

%time perl diff.new -u bc bc.new > /dev/null
real	0m9.470s
...
real	0m9.546s
...
real	0m9.329s
  • Loading branch information
mknos authored Jan 8, 2025
1 parent 320d267 commit 46f717e
Showing 1 changed file with 6 additions and 9 deletions.
15 changes: 6 additions & 9 deletions bin/diff
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,8 @@ package

use strict;

use List::Util qw(max);

our $VERSION = '0.57';

sub LCS_matrix {
Expand All @@ -626,23 +628,18 @@ sub LCS_matrix {
$al = @$a;
$bl = @$b;

my ($i, $j);

$x[0] = [(0) x ($bl+1)];
for ($i=1; $i<=$al; $i++) {
my $r = $x[$i] = [];
$r->[0] = 0;
for ($j=1; $j<=$bl; $j++) {
for my $i (1 .. $al) {
my $r = $x[$i] = [ 0 ];
for my $j (1 .. $bl) {
# If the first two items are the same...
if (defined $eq
? $eq->($a->[-$i], $b->[-$j])
: $a->[-$i] eq $b->[-$j]
) {
$r->[$j] = 1 + $x[$i-1][$j-1];
} else {
my $pi = $x[$i][$j-1];
my $pj = $x[$i-1][$j];
$r->[$j] = ($pi > $pj ? $pi : $pj);
$r->[$j] = max($x[$i][$j-1], $x[$i-1][$j]);
}
}
}
Expand Down

0 comments on commit 46f717e

Please sign in to comment.