[Israel.pm] C style for loop

sawyer x xsawyerx at gmail.com
Sat Feb 25 15:01:26 PST 2012


On Sat, Feb 25, 2012 at 10:14 PM, Yossi Itzkovich <
Yossi.Itzkovich at ecitele.com> wrote:

> Hi
>
> This solution makes it run slower, isn't it ?  Since Perl has to use
> access-by-index, isn't it ?
>

Not at all.

If you write it using a C-style for loop, you would still need to access by
index:
for ( my $i = 0; $i < @array; $i++ ) {
    my $item = $array[$i];
}
vs.
for my $i ( 0 .. $#array ) {
    my $item = $array[$i];
}

I actually went and benchmarked it. Using $#array or scalar context @array
turned out to be slower. How much slower? Twice as much! If you calculate
the array size in advance, it will be *exactly* the same speed. :)
C-style loop uses a cached array size, C-style loop 2 used $#array. (with
@array it was pretty much the same)

Benchmark: timing 100000 iterations of C-style, C-style2, foreach...
   C-style:  0 wallclock secs ( 0.47 usr +  0.00 sys =  0.47 CPU) @
212765.96/s (n=100000)
  C-style2:  1 wallclock secs ( 0.92 usr +  0.00 sys =  0.92 CPU) @
108695.65/s (n=100000)
   foreach:  1 wallclock secs ( 0.47 usr +  0.00 sys =  0.47 CPU) @
212765.96/s (n=100000)

Here is a more detailed benchmark. You'll see here that C-style with
pre-calculated array size was a tiny bit faster than the foreach, but I see
it as a margin of error in the benchmark because sometimes the foreach is
faster.
Benchmark: timing 500000 iterations of C-style $#array, C-style @array,
C-style known size, foreach...
C-style $#array:  3 wallclock secs ( 4.56 usr +  0.00 sys =  4.56 CPU) @
109649.12/s (n=500000)
C-style @array:  4 wallclock secs ( 3.85 usr +  0.00 sys =  3.85 CPU) @
129870.13/s (n=500000)
C-style known size:  3 wallclock secs ( 2.28 usr +  0.00 sys =  2.28 CPU) @
219298.25/s (n=500000)
   foreach:  3 wallclock secs ( 2.39 usr +  0.00 sys =  2.39 CPU) @
209205.02/s (n=500000)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.perl.org.il/pipermail/perl/attachments/20120226/0c8a22b6/attachment.htm 


More information about the Perl mailing list