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


in reply to Re: counting backward
in thread counting backward

It seems that your output and the output of BrowserUk brings the different results ( Re^5: counting backward (optimize foreach reverse low .. high ).

I noticed that you print in the loop and BrowserUk calls '1'. I tried to run the both versions and found that it brings the different results indeed:

Loops with print (I used a NULL device to keep it clear, s.below): Rate foreach_loop c_for_loop foreach_loop 256/s -- -8% c_for_loop 278/s 8% -- Loops with '1': Rate c_for_loop foreach_loop c_for_loop 1314/s -- -22% foreach_loop 1674/s 27% --
The code (your code :-):
#! perl use strict; use warnings; use IO::Null; =pod PM Thread perlquestion [id://1021418] =cut use Benchmark qw( cmpthese ); my $n = 1e4; my $null = IO::Null->new; cmpthese ( 10000, { foreach_loop => \&foreach_loop, c_for_loop => \&c_for_loop, } ); sub foreach_loop { for my $i (-$n .. 0) { # $null->print( -$i ); 1; } } sub c_for_loop { for (my $j = $n; $j >= 0; --$j) { # $null->print( $j ); 1; } }