Optimisation

Andy Armstrong andy at hexten.net
Mon Mar 2 21:22:47 GMT 2009


On 2 Mar 2009, at 21:11, Andy Armstrong wrote:
>> Or is it a pointless question?
>
>
> Yes :)
>
> Benchmark it - but I bet there's not much difference - and the  
> second version will be faster in the non-empty case.


Oooh:

$ cat bm-foolish-idea.pl
#!/usr/bin/env perl

use strict;
use warnings;
use Benchmark qw( cmpthese );

my @empty     = ();
my @non_empty = ( 1 );

cmpthese - 1, {
   empty_if_foreach => sub {
     if ( @empty ) {
       foreach ( @empty ) {
         $_ += 0;
       }
     }
   },
   empty_foreach => sub {
     foreach ( @empty ) {
       $_ += 0;
     }
   },
};

cmpthese - 1, {
   non_empty_if_foreach => sub {
     if ( @non_empty ) {
       foreach ( @non_empty ) {
         $_ += 0;
       }
     }
   },
   non_empty_foreach => sub {
     foreach ( @non_empty ) {
       $_ += 0;
     }
   },
};

# vim:ts=2:sw=2:sts=2:et:ft=perl


$ perl bm-foolish-idea.pl
                        Rate    empty_foreach empty_if_foreach
empty_foreach     5242880/s               --             -74%
empty_if_foreach 20309304/s             287%               --
                           Rate non_empty_if_foreach     
non_empty_foreach
non_empty_if_foreach 1203020/s                   --                 -17%
non_empty_foreach    1456355/s                  21%                   --

Well whadya know?

-- 
Andy Armstrong, Hexten



More information about the london.pm mailing list