Perl Benchmark IN sub with grep

If you miss the IN function in Perl like the function in PL/SQL, then you could use grep and an array to check this:

grep {$var eq $_} qw(2 3 5 7 11 13 17 19)

I made a Benchmark to check how fast his solution is:

use strict;
use Benchmark qw(:all) ;

my @data = qw(2 3 5 7 11 13 17 19);
cmpthese(-2, {
'grep0'  => sub {
        for my $var (1..20){
            if(grep {$var == $_} qw(2 3 5 7 11 13 17 19)){
               # print "$var is prime!".$/;
            }else{
               # print "$var is not prime!".$/;
            }
        }
    },
'grep1'  => sub {
        for my $var (1..20){
            if(grep {$var == $_} @data){
               # print "$var is prime!".$/;
            }else{
               # print "$var is not prime!".$/;
            }
        }
    },
'or'   => sub {
        for my $var (1..20){
            if($var==2||$var==3||$var==5||$var==7||$var==11||$var==13||$var==17||$var==19){
               # print "$var is prime!".$/;
            }else{
               # print "$var is not prime!".$/;
            }
        }
    },
});

Result:

          Rate grep0 grep1    or  
grep0  74471/s    --   -7%  -61%  
grep1  79714/s    7%    --  -58%  
or    189402/s  154%  138%    --

We see the normal way is the fastest and you could use an defined array to speed up by 7%. The Code is short but much slower than an or comparison.

2 thoughts on “Perl Benchmark IN sub with grep”

  1. Hello everyone, it’s my first go to see at this site, and piece of writing is actually fruitful designed
    for me, keep up posting these posts.

  2. Hey very nice blog!! Guy .. Beautiful .. Wonderful
    .. I will bookmark your blog and take the feeds additionally?

    I’m glad to seek out numerous helpful info right here within the
    put up, we need develop extra strategies in this regard, thank you for sharing.
    . . . . .

Leave a Reply

Your email address will not be published.

eight − 6 =