A note on performance:
Two optimizations are needed for "Perl-style" for my $i (reverse 0..$#a) to be as fast as the "C-style" for loop: 1) The elimination of reverse by processing the list backwards, and 2) the treatment of 0..$#a as an interator instead of flattening it. Not all versions of perl implement both of these implementations. As such, it's slower in some versions. (Update: 5.8.6 added (1). (2) still missing when reverse is used. c.f. Re^4: the '..' operator and decreasing values)
This is perl, v5.6.1 built for MSWin32-x86-multi-thread
Rate ickyb0d ickyb0d_ perl_for diotalevi while_loop c
+_style_for
ickyb0d 2516/s -- -8% -44% -48% -52%
+ -52%
ickyb0d_ 2726/s 8% -- -40% -43% -48%
+ -48%
perl_for 4507/s 79% 65% -- -6% -14%
+ -14%
diotalevi 4794/s 91% 76% 6% -- -9%
+ -9%
while_loop 5261/s 109% 93% 17% 10% --
+ -0%
c_style_for 5261/s 109% 93% 17% 10% 0%
+ --
Still, the Perl-style for loop is not much slower (14% slower, maybe less for smaller arrays) than the C-style for loop even in "old" version 5.6.1.
Update: Added diotalevi's solution.
|