in reply to Macro in perl code?

I don't have an answer to your question, just a remark.

sub v_print { my $volume = shift; my $message = shift;
modifies @_ although it doesn't have to. Changing that to my ($volume, $message) = @_; should speed it up a little bit.

Replies are listed 'Best First'.
Re^2: Macro in perl code?
by bruceb3 (Pilgrim) on Oct 16, 2007 at 18:47 UTC
    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% --
      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% --
Re^2: Macro in perl code?
by vrk (Chaplain) on Oct 16, 2007 at 20:25 UTC

    Actually, for some time I have used the following convention in object-oriented modules:

    sub func { my $self = shift; my ($param1, $param2, ..., $paramn) = @_; # ... }

    Motivation: you "slurp" the calling object, after which it is clearer which are actually parameters to the method.

    (Sorry for OT.)

    Update: changed "my func" to "sub func". Silly me.

    --
    print "Just Another Perl Adept\n";