Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster way to check for element in array?

Tags:

arrays

perl

This function does the same as exists does with hashes.

I plan on use it a lot.

Can it be optimized in some way?

my @a = qw/a b c d/;

my $ret = array_exists("b", @a);

sub array_exists {
    my ($var, @a) = @_;

    foreach my $e (@a) {
        if ($var eq $e) {
            return 1;
        }
    }
    return 0;
}
like image 209
Sandra Schlichting Avatar asked Aug 04 '11 13:08

Sandra Schlichting


People also ask

Which array method is faster?

In case of multiple iterations of the loop, and where the size of array is too large, for loop is the preference as the fastest method of elements' iteration. While loops perform efficient scaling in case of large arrays. In case of functional codes, for each loop performs better with a much optimized time.

What's faster than a for loop?

Conclusions. List comprehensions are often not only more readable but also faster than using “for loops.” They can simplify your code, but if you put too much logic inside, they will instead become harder to read and understand.

How do I find an element in an array of arrays?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.


2 Answers

If you have to do this a lot on a fixed array, use a hash instead:

 my %hash = map { $_, 1 } @array;

 if( exists $hash{$key} ) { ... }

Some people reach for the smart match operator, but that's one of the features that we need to remove from Perl. You need to decide if this should match, where the array hold an array reference that has a hash reference with the key b:

use 5.010;

my @a = (
    qw(x y z),
    [ { 'b' => 1 } ],
    );

say 'Matches' if "b" ~~ @a; # This matches

Since the smart match is recursive, if keeps going down into data structures. I write about some of this in Rethinking smart matching.

like image 70
brian d foy Avatar answered Oct 16 '22 02:10

brian d foy


You can use smart matching, available in Perl 5.10 and later:

if ("b" ~~ @a) {
    # "b" exists in @a
}

This should be much faster than a function call.

like image 42
Eugene Yarmash Avatar answered Oct 16 '22 02:10

Eugene Yarmash