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;
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 haveO(N)accesses of the list, andO(1)memory usage.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
reducesolution:which results in the following benchmark: