<?xml version="1.0" encoding="windows-1252"?>
<node id="723871" title="Re^6: C-style for loop" created="2008-11-15 20:42:17" updated="2008-11-15 20:42:17">
<type id="11">
note</type>
<author id="381608">
ikegami</author>
<data>
<field name="doctext">
&lt;ul&gt;
&lt;li&gt;For &lt;c&gt;for (X..Y)&lt;/c&gt;, Perl uses a counting loop.
&lt;li&gt;For &lt;c&gt;for (reverse constX..constY)&lt;/c&gt;, Perl builds a flattened list at compile-time and iterates over it in reverse.
&lt;li&gt;For &lt;c&gt;for (reverse X..Y)&lt;/c&gt;, Perl builds a flattened list at run-time and iterates over it in reverse.
&lt;/ul&gt;

&lt;p&gt;So far, I've found 6 different kinds of for loops in Perl. You can find them in [id://594208|an earlier node].

&lt;c&gt;
#!/usr/bin/perl --
use strict;
use warnings;

use Benchmark qw(cmpthese);

my $BIG = 100_000;

cmpthese(-3, {
   c_f  =&gt; \&amp;c_f,
   c_r  =&gt; \&amp;c_r,
   p_fv =&gt; \&amp;p_fc,
   p_fc =&gt; \&amp;p_fv,
   p_rc =&gt; \&amp;p_rc,
   p_rv =&gt; \&amp;p_rv,
});

sub c_f  { for (my $i = 0; $i &lt; $BIG; $i++  ) { 1 } }
sub c_r  { for (my $i = $BIG; $i-- &gt; 0;     ) { 1 } }
sub p_fc { for my $i (         0..100_000-1 ) { 1 } }
sub p_fv { for my $i (         0..$BIG-1    ) { 1 } }
sub p_rc { for my $i ( reverse 0..100_000-1 ) { 1 } }
sub p_rv { for my $i ( reverse 0..$BIG-1    ) { 1 } }

__END__

       Rate p_rv  c_r  c_f p_rc p_fv p_fc
p_rv 28.5/s   -- -37% -44% -59% -64% -65%  Builds list and loops.
c_r  45.0/s  58%   -- -11% -35% -44% -44%
c_f  50.7/s  78%  13%   -- -27% -37% -37%
p_rc 69.7/s 144%  55%  37%   -- -13% -14%  Loops over pre-built array.
p_fv 80.0/s 180%  78%  58%  15%   --  -1%  Counting loop
p_fc 80.7/s 183%  79%  59%  16%   1%   --  Counting loop
&lt;/c&gt;

&lt;p&gt;If you add "&lt;c&gt;(),&lt;/c&gt;" to the front of any of the lists, you'll notice that p_* will become as slow as p_rv.
</field>
<field name="root_node">
723825</field>
<field name="parent_node">
723853</field>
</data>
</node>
