Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The fastest way (execution time) to find the longest element in an list

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;
like image 265
sid_com Avatar asked Nov 15 '10 06:11

sid_com


People also ask

How do you find the longest element in a list?

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 .

How do you find max length in python?

In this, we use inbuilt max() with “len” as key argument to extract the string with the maximum length.

How do you find the longest string in an array?

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.


1 Answers

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%      --
like image 118
Eric Strom Avatar answered Oct 29 '22 15:10

Eric Strom