http://www.perlmonks.org?node_id=1021565


in reply to Re^2: counting backward
in thread counting backward

vagabonding electron,

You are correct that a foreach loop is faster than a C-style for loop, other things being equal. As BrowserUk has explained, this is because with the latter, but not the former,

you must always pay the penalty of creating a new scope for each iteration of the loop.

But my point was that if you count upwards from -$n, you add the overhead of a unary negation operator when you come to actually use the original $n:

#! perl use strict; use warnings; use Benchmark qw( cmpthese ); my $n = 1e6; my $foreach_loop_total = 0; my $c_for_loop_total = 0; cmpthese ( 1000, { foreach_loop => \&foreach_loop, c_for_loop => \&c_for_loop, } ); print "\$foreach_loop_total = $foreach_loop_total\n"; print "\$c_for_loop_total = $c_for_loop_total\n"; sub foreach_loop { $foreach_loop_total += -$_ for -$n .. 0; } sub c_for_loop { for (my $j = $n; $j >= 0; --$j) { $c_for_loop_total += $j; } }

Output:

12:00 >perl 555_SoPW.pl Rate foreach_loop c_for_loop foreach_loop 5.62/s -- -8% c_for_loop 6.13/s 9% -- $foreach_loop_total = 500000500000000 $c_for_loop_total = 500000500000000 12:05 >

So, it appears that the overhead of the additional negation outweighs the benefit of not having to create a new scope on each iteration.

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,