Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: How foreach loops decide what to iterate through

by Lawliet (Curate)
on Feb 13, 2009 at 23:27 UTC ( #743736=note: print w/ replies, xml ) Need Help??


in reply to How foreach loops decide what to iterate through

Welcome to The Monastery, and thank you for writing your node.

I have little experience with the Benchmark module, but after conducting some tests, I would say that you should use the latter method, the one you prefer. It is more concise, easier to read, and a little more efficient. (thanks for the notice, ikegami.)

#!/usr/bin/perl use warnings; use strict; use 5.010; use Benchmark qw(:all); use Data::Dumper; cmpthese(100000, { 'LowOutside' => sub { my @array = qw(8 1 3 5 6 2); @array = sort @array; foreach (@array) { my $num = $_; } }, 'LowInside' => sub { my @array = qw(8 1 3 5 6 2); foreach (sort @array) { my $num = $_; } }, 'Outside' => sub { my @array = qw(8 1 3 5 6 2) x 100; @array = sort @array; foreach (@array) { my $num = $_; } }, 'Inside' => sub { my @array = qw(8 1 3 5 6 2) x 100; foreach (sort @array) { my $num = $_; } } }); __END__ Rate Outside Inside LowOutside LowInside Outside 1681/s -- -1% -99% -99% Inside 1691/s 1% -- -99% -99% LowOutside 169492/s 9985% 9924% -- -5% LowInside 178571/s 10525% 10461% 5% --

And you didn't even know bears could type.


Comment on Re: How foreach loops decide what to iterate through
Download Code
Re^2: How foreach loops decide what to iterate through
by ikegami (Pope) on Feb 14, 2009 at 03:09 UTC

    I would say that you should use the latter method, the one you prefer. It is more concise, easier to read, and a little more efficient.

    1% and even 5% is within the margin or error of Benchmark, so that last phrase is inaccurate.

    I'm actually surprised they're the same speed. @a = sort @a; is optimized to be done in place, and I think for (@a) is optimized over the more general for (LIST) (it's definitely implemented differently).

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://743736]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (9)
As of 2014-10-02 16:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (65 votes), past polls