Perl && vs. and – || vs. or Benchmark

I want to compare the && vs. the and operator, and the || vs. or operator in Perl:

#!/usr/bin/perl
use strict;
use Benchmark qw(:all) ;
 
my $x = 100;
my $y = 0;
 
cmpthese(-1, {
'and'  => sub {if($y and $x){print;}print;},
'&&'   => sub {if($y &&  $x){print;}print;},
});
cmpthese(-1, {
'or'   => sub {if($y or  $x){print;}print;},
'||'   => sub {if($y ||  $x){print;}print;},
});
 
++$y;

cmpthese(-1, {
'and'  => sub {if($y and $x){print;}print;},
'&&'   => sub {if($y &&  $x){print;}print;},
});
cmpthese(-1, {
'or'   => sub {if($y or  $x){print;}print;},
'||'   => sub {if($y ||  $x){print;}print;},
});

 

First result (1 && 0) vs. (1 and 0):

         Rate  && and  
&&  4497569/s  -- -3%  
and 4626070/s  3%  --

Second result (1 or 0) vs. (1 || 0):

        Rate   or   || 
or 2683073/s   -- -15% 
|| 3163806/s  18%   --

Third result (1 && 1) vs. (1 and 1):

         Rate  && and  
&&  2525239/s  -- -1%  
and 2548621/s  1%  --

Fourth result (1 or 1) vs. (1 || 1):

        Rate   or   || 
or 2912710/s   -- -33% 
|| 4324590/s  48%   --

It seems the “and” and “&&” don’t make really different, but the “or” and “||” operator seems different.I don’t know why the “||” are 18-48% faster than the “or” …. and the “and” is only about 1-3% faster.

 

Now we check if they work as they should:

if(false() and true()){print;}print"END\n";
if(false() &&  true()){print;}print"END\n";
if(false() or  true()){print;}print"END\n";
if(false() ||  true()){print;}print"END\n";

 
if(true() and true()){print;}print"END\n";
if(true() &&  true()){print;}print"END\n";
if(true() or  true()){print;}print"END\n";
if(true() ||  true()){print;}print"END\n";


sub true() {print "sub true";return(1);}
sub false() {print "sub false";return(0);}

result looks good they abort if a true is impossible:

sub falseEND        
sub falseEND        
sub falsesub trueEND
sub falsesub trueEND
sub truesub trueEND 
sub truesub trueEND 
sub trueEND         
sub trueEND

That is more a check up and not really a Benchmark.

5 thoughts on “Perl && vs. and – || vs. or Benchmark”

  1. What’s up to all, how is all, I think every one is getting more from this web site, and yourr views are pleasant designed for new visitors.

  2. Pretty! This has been an extremely wonderful article.

    Thank you for supplying these details.

Leave a Reply

Your email address will not be published.

four × five =