http://qs321.pair.com?node_id=723859


in reply to Re^5: C-style for loop
in thread C-style for loop

Absolutely if the point you are trying to make is that there is a tiny execution penalty in this rather artificial case for using the Perl style for loop. An interesting test is to change the loops from reverse to forwards and see where the differences lie. For the C style for loop you need to change every part of the loop header in a major way and you have to think a while to ensure the range is what you want:

for (my $i = $BIG; $i > 0; $i--) { becomes for (my $i = 0; $i <= $BIG; $i++) {

For the Perl loop just deleting the reverse does the trick and the range is still completely clear. Oh, and now the Perl loop overhead is less than the C loop overhead:

#!/usr/bin/perl -- use strict; use warnings; use Benchmark qw(cmpthese); my $BIG = 100_000; print "c: ", c (),"\n"; print "p: ", p (),"\n"; print "cF: ", cF (),"\n"; print "pF: ", pF (),"\n"; cmpthese(-1, { 'C-style' => \&c, 'P-style' => \&p, 'C-styleF' => \&cF, 'P-styleF' => \&pF, }); sub c { my $sum = 1; for (my $i = $BIG; $i > 0; $i--) { $sum += $i; } return $sum; } sub p { my $sum = 1; for my $i ( reverse 1..$BIG ) { $sum += $i; } return $sum; } sub cF { my $sum = 1; for (my $i = 1; $i <= $BIG; $i++) { $sum += $i; } return $sum; } sub pF { my $sum = 1; for my $i ( 1..$BIG ) { $sum += $i; } return $sum; } __END__ c: 5000050001 p: 5000050001 cF: 5000050001 pF: 5000050001 Rate P-style C-style C-styleF P-styleF P-style 49.9/s -- -23% -33% -42% C-style 65.0/s 30% -- -13% -25% C-styleF 74.7/s 50% 15% -- -13% P-styleF 86.2/s 73% 33% 15% --

Considering how small the overhead of using reverse is and how much more maintainable the Perl loop is you have done an admirable job of demonstrating why in the general case the Perl for loop is much better than the C style for loop.


Perl reduces RSI - it saves typing