Your skill will accomplishwhat the force of many cannot 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??

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 (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).

Create A New User
Node Status?
node history
Node Type: note [id://743736]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (7)
As of 2018-06-20 08:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Should cpanminus be part of the standard Perl release?

Results (116 votes). Check out past polls.

Notices?