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% --
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…