in reply to Re: Macro in perl code?
in thread Macro in perl code?

I don't know if there is any real value in benchmarking this because it may change from different vesion of Perl but the results would indicate that using shift is faster.
#!/usr/bin/env perl use strict; use warnings; use Benchmark qw/ cmpthese /; cmpthese(10000000, { shift => sub { my $volume = shift; my $message = shift; }, inline => sub { my ($volume, $message) = @_ } } );
And the output is -
bruce:0:~/tmp $ ./p.pl Rate inline shift inline 3300330/s -- -29% shift 4629630/s 40% --

Replies are listed 'Best First'.
Re^3: Macro in perl code?
by andreas1234567 (Vicar) on Oct 16, 2007 at 19:20 UTC
    Adding some overhead in the subroutine being called, the difference (if any) between the two approaches disappears altogether:
    $ cat 645237.pl use strict; use warnings; use Benchmark qw/ cmpthese /; use List::Util qw/ sum /; sub foo { my ($volume, $message) = @_; my @foo = ($volume .. $message); @foo = map { $_ ** 2 } @foo; return sum(@foo); } sub bar { my $volume = shift; my $message = shift; my @foo = ($volume .. $message); @foo = map { $_ ** 2 } @foo; return sum(@foo); } cmpthese(100_000, { shift => sub { foo(1, 100) }, inline => sub { bar(1, 100) }, } ); $ perl 645237.pl Rate inline shift inline 8396/s -- -0% shift 8403/s 0% --
    If your Benchmark shows your computer is able to perform an operation 3 million times pr. second, that's equivalent of a 1000 m2 highway sign saying: Don't optimize!

    Update: Changed code to supply arguments to functions as pointed out by bruceb3.

    --
    Andreas
      What is interesting is that the code that you benchmarked and the code that I benchmarked, doesn't actually supply arguments to the either function, which really is the point after all.

      Changing the cmpthese call to;

      cmpthese(100_000, { shift => sub { foo(1, "foo") }, inline => sub { bar(1, "bar") } });

      The results are the same for either method;

      bruce:0:~/tmp $ ./535237.pl Rate shift inline shift 15456/s -- -0% inline 15528/s 0% --