Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monks,

Is
foreach ($a, $b, $c, $d) { tr/a-z/A-Z/; }
Quicker than:
for my $i ($a, $b, $c, $d) { $i =~ tr/a-z/A-Z/; }
???
The question is, does assigning $i use up more processing power than where simply using the default variable would?

Thanks,
Jonathan

Replies are listed 'Best First'.
Re: default variable question
by dragonchild (Archbishop) on Feb 07, 2006 at 15:42 UTC
    A few truisms:
    • 90% of all runtime is located in 10% of an application's code.
    • At least 90% of all speedups are achieved through algorithm improvements.

    If you're worried about the 3 extra femtoseconds that the slower chose might take, then you shouldn't be programming in Perl. Unless, of course, you're curious about the internals of Perl and how exactly everything works. In which case, I would suggest rephrasing your question. :-)


    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
Re: default variable question
by adrianh (Chancellor) on Feb 07, 2006 at 15:30 UTC

    Learn to use Benchmark and find out :-)

    Even better learn to use one of the profile modules and forget about micro-optimisations until you know you actually need them.

Re: default variable question
by duff (Parson) on Feb 07, 2006 at 15:40 UTC

    Sorry, but that seems like a ridiculus question. But, the answer is yes. Perl has to allocate $i where otherwise it wouldn't. But I'll wager the difference is so negligible that you'd never notice.

      safe bet!

      #!/usr/bin/perl use Benchmark qw(:all); my $count = 1000000; timethese($count, { 'Name1' => sub { my( $a, $b, $c, $d ) = qw( kookla fran and ollie ); foreach ($a, $b, $c, $d) { tr/a-z/A-Z/; } }, 'Name2' => sub { my( $a, $b, $c, $d ) = qw( kookla fran and ollie ); for my $i ($a, $b, $c, $d) { $i =~ tr/a-z/A-Z/; } }, });

      gives me:

      Benchmark: timing 1000000 iterations of Name1, Name2... Name1: 15 wallclock secs (15.70 usr + 0.08 sys = 15.78 CPU) @ 63 +371.36/s (n=1000000) Name2: 15 wallclock secs (15.31 usr + 0.02 sys = 15.33 CPU) @ 65 +231.57/s (n=1000000)
      -derby

        My results were a little different (using Perl 5.8.7 on Windows). I got:

        Name1: 42 wallclock secs (36.77 usr + -0.00 sys = 36.76 CPU) @ 272005. +22/s (n=10000000) Name2: 49 wallclock secs (42.80 usr + 0.03 sys = 42.83 CPU) @ 233486. +66/s (n=10000000)

        And then:

        Name1: 42 wallclock secs (36.52 usr + 0.08 sys = 36.59 CPU) @ 273268. +84/s (n=10000000) Name2: 42 wallclock secs (36.47 usr + 0.00 sys = 36.47 CPU) @ 274213. +01/s (n=10000000)

        I don't know what is making the difference with these results, unless it's other programs getting CPU time.

      Ah but you forget that while the first doesn't need to create lexical $i, it does need to localize $_.