Is this the fastest (execution time) way to find the longest element in a list?
#!/usr/bin/env perl
use warnings;
use 5.012;
use List::Util qw(reduce);
use List::Util::XS;
my @array = qw( one two three four five six seven eight nine ten eleven );
my $l = reduce{ length($a) > length($b) ? $a : $b } @array;
say $l;
Use max() to find the longest string in a list. Call max(a_list, key=len) to return the longest string in a_list by comparing the lengths of all strings in a_list .
In this, we use inbuilt max() with “len” as key argument to extract the string with the maximum length.
To find the string with the most length, we can loop over the strings in the array, compare the length of the current string to the longest string up until that point, and then if the current string is longer, we make that the new longest string.
When only trying to find one element of a list, there is no need to construct an N sized data structure as many answers here have done. The fastest O(N)
way to do this is to walk the array, keeping track of the largest element. That way you have O(N)
accesses of the list, and O(1)
memory usage.
sub longest {
my $max = -1;
my $max_i = 0;
for (0 .. $#_) { # for each index
my $len = length $_[$_]; # only get length once per item
if ($len > $max) { # save index and update max if larger
$max = $len;
$max_i = $_;
}
}
$_[$max_i] # return the largest item
}
If you are going to be running the above code many times, I would suggest inlining the body of the subroutine.
EDIT:
drewk's benchmark revealed that the array index in the above code is a bit of a bottleneck. Experimenting a little more, I have finally found a method that is faster than the reduce
solution:
sub fastest {
my $max = -1;
my $max_ref;
for (@_) {
if (length > $max) { # no temp variable, length() twice is faster
$max = length;
$max_ref = \$_; # avoid any copying
}
}
$$max_ref
}
which results in the following benchmark:
Rate longest drewk reduce fastest
longest 44245/s -- -21% -30% -47%
drewk 55854/s 26% -- -11% -33%
reduce 63014/s 42% 13% -- -25%
fastest 83638/s 89% 50% 33% --
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With