Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: How foreach loops decide what to iterate through

by Lawliet (Curate)
on Feb 13, 2009 at 23:27 UTC ( [id://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.

Replies are listed 'Best First'.
Re^2: How foreach loops decide what to iterate through
by ikegami (Patriarch) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://743736]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2024-03-28 19:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found