Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re^2: counting backward

by BrowserUk (Patriarch)
on Mar 03, 2013 at 19:15 UTC ( [id://1021525]=note: print w/replies, xml ) Need Help??


in reply to Re: counting backward
in thread counting backward

Cute! But ...

It forces the use of post increment which is more costly that pre increment. And there is no need to explicitly compare to 0.

Avoiding those and it comes out quicker than the block form of foreach:

#! perl use strict; use warnings; #use IO::Null; use Benchmark qw( cmpthese ); my $n = 1e4; #my $null = IO::Null->new; cmpthese 10000, { foreach_loop => \&foreach_loop, foreach_modifier => \&foreach_modifier, c_for_loop => \&c_for_loop, c_for_loop2 => \&c_for_loop2, c_for_loop3 => \&c_for_loop3, c_for_loop4 => \&c_for_loop4, }; sub foreach_loop { for my $i (-$n .. 0) { # $null->print( -$i ); 1; } } sub foreach_modifier { 1 for -$n .. 0; } sub c_for_loop { for (my $j = $n; $j >= 0; --$j) { # $null->print( $j ); 1; } } sub c_for_loop2 { for (my $j = $n; $j-- > 0; ) { # $null->print( $j ); 1; } } sub c_for_loop3 { for (my $j = $n; --$j > 0; ) { # $null->print( $j ); 1; } } sub c_for_loop4 { for (my $j = $n; --$j; ) { # $null->print( $j ); 1; } } __END__ C:\test>junk Rate c_for_loop2 c_for_loop c_for_loop3 foreach_loo +p c_for_loop4 foreach_modifier c_for_loop2 807/s -- -13% -38% -50 +% -53% -56% c_for_loop 926/s 15% -- -29% -43 +% -46% -50% c_for_loop3 1298/s 61% 40% -- -19 +% -24% -29% foreach_loop 1612/s 100% 74% 24% - +- -6% -12% c_for_loop4 1707/s 111% 84% 31% 6 +% -- -7% foreach_modifier 1839/s 128% 99% 42% 14 +% 8% --

But still the modifier form wins.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1021525]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-03-19 05:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found