vinoth.ree has asked for the wisdom of the Perl Monks concerning the following question:

In the following foreach loop I used $num variable to hold the each array elements in another foreach loop I used $_, which foreach loop will be efficient ?

my @numbers = (1,2,3,4,5); foreach my $num (@numbers){ print "$num\n"; }
my @numbers = (1,2,3,4,5); foreach (@numbers){ print "$_\n"; }

Replies are listed 'Best First'.
Re: Variable usage
by ambrus (Abbot) on Mar 05, 2009 at 07:23 UTC
    I would like to know which of the following loops is more efficient

    No, you would not like to know that. Don't try to prematurely optimize please.

      If the OP were to persist in prematurely optimizing, of course, the only thing you could meaningfully optimize this code for would be the number of bytes of code, in which case the naive solution for the critical section would be

      $\ = $/; print foreach (@numbers);
      Though at that point, we've opened the door into whole new realms of time-wasting. ;-)



      If God had meant us to fly, he would *never* have given us the railroads.
          --Michael Flanders

        $, = $\ = $/; print @numbers;
        Or in 5.10...
Re: Variable usage
by bart (Canon) on Mar 05, 2009 at 08:14 UTC

    print will waste a lot more time (think: several orders of magnitude) than anything else that happens in that loop. You're just wasting your time. Even if one type of loop variable is double the speed than the other (and trust me, that won't be the case), you still will not notice, at all.

    And if you have legitimate reasons to optimize things, try Benchmark first, to compare execution times of equivalent code snippets, and one of the "Profile" modules on CPAN to see where your module is really wasting time. The latest buzz is that Devel::NYTProf is currently the best module for that purpose.

Re: Variable usage
by ikegami (Patriarch) on Mar 05, 2009 at 07:36 UTC
    Depends, how many million times per second is the code containing this loop executed? I'm guessing "around zero", in which case the answer is "there's no difference".