Skip to content

Commit 46f717e

Browse files
authored
diff: simplify LCS_matrix() (#915)
* 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
1 parent 320d267 commit 46f717e

File tree

1 file changed

+6
-9
lines changed

1 file changed

+6
-9
lines changed

bin/diff

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -609,6 +609,8 @@ package
609609

610610
use strict;
611611

612+
use List::Util qw(max);
613+
612614
our $VERSION = '0.57';
613615

614616
sub LCS_matrix {
@@ -626,23 +628,18 @@ sub LCS_matrix {
626628
$al = @$a;
627629
$bl = @$b;
628630

629-
my ($i, $j);
630-
631631
$x[0] = [(0) x ($bl+1)];
632-
for ($i=1; $i<=$al; $i++) {
633-
my $r = $x[$i] = [];
634-
$r->[0] = 0;
635-
for ($j=1; $j<=$bl; $j++) {
632+
for my $i (1 .. $al) {
633+
my $r = $x[$i] = [ 0 ];
634+
for my $j (1 .. $bl) {
636635
# If the first two items are the same...
637636
if (defined $eq
638637
? $eq->($a->[-$i], $b->[-$j])
639638
: $a->[-$i] eq $b->[-$j]
640639
) {
641640
$r->[$j] = 1 + $x[$i-1][$j-1];
642641
} else {
643-
my $pi = $x[$i][$j-1];
644-
my $pj = $x[$i-1][$j];
645-
$r->[$j] = ($pi > $pj ? $pi : $pj);
642+
$r->[$j] = max($x[$i][$j-1], $x[$i-1][$j]);
646643
}
647644
}
648645
}

0 commit comments

Comments
 (0)