Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: counting backward

by tobyink (Abbot)
on Mar 03, 2013 at 18:55 UTC ( #1021524=note: print w/ replies, xml ) Need Help??


in reply to counting backward

Have you tried the magic descendi rocket? (-->)

use strict; use warnings; foreach (my $i = 11; $i --> 0;) { print "$i "; } print "\n";
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name


Comment on Re: counting backward
Select or Download Code
Re^2: counting backward
by BrowserUk (Pope) on Mar 03, 2013 at 19:15 UTC

    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
Node Status?
node history
Node Type: note [id://1021524]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (14)
As of 2014-09-16 18:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (40 votes), past polls