in reply to counting backward
I’m a little surprised no-one has suggested a good, old-fashioned, C-style for loop. If speed is a factor, it’s a clear winner over foreach-with-negation:
#! perl use strict; use warnings; use Benchmark qw( cmpthese ); my $n = 1e4; cmpthese ( 100, { foreach_loop => \&foreach_loop, c_for_loop => \&c_for_loop, } ); sub foreach_loop { for my $i (-$n .. 0) { print -$i; } } sub c_for_loop { for (my $j = $n; $j >= 0; --$j) { print $j; } }
Output (end only):
Rate foreach_loop c_for_loop foreach_loop 89.0/s -- -69% c_for_loop 292/s 227% -- 2:32 >
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: counting backward
by vagabonding electron (Curate) on Mar 03, 2013 at 16:33 UTC | |
by BrowserUk (Patriarch) on Mar 03, 2013 at 18:40 UTC | |
by Athanasius (Archbishop) on Mar 04, 2013 at 02:20 UTC | |
by BrowserUk (Patriarch) on Mar 04, 2013 at 03:28 UTC |