in reply to Re: Checking for value in an array (without FOR)
in thread [untitled node, ID 160640]
That faq is somewhat out of date, as recent perls have been optimized such that map and grep don't build return lists if they're not required. As the benchmarking code below shows (numbers generated with 5.6.1 on a 1.2G Athlon):
#!/usr/bin/perl use Benchmark qw( timethese cmpthese ); my @args = ( 100_000, { void => sub { grep { $_ == 50 } 0..100; 1 }, scalar => sub { my $res = grep { $_ == 50 } 0..100 }, list => sub { my @res = grep { $_ == 50 } 0..100 }, a_foreach => sub { my $match; foreach( 0..100 ) { $match++ if $_ == 50 } $match } } ); cmpthese( @args ); exit 0; __END__
Benchmark: timing 100000 iterations of a_foreach, list, scalar, void...
a_foreach: 4 wallclock secs ( 4.52 usr + 0.01 sys = 4.53 CPU) @ 22075.06/s (n=100000)
list: 4 wallclock secs ( 3.35 usr + 0.00 sys = 3.35 CPU) @ 29850.75/s (n=100000)
scalar: 3 wallclock secs ( 3.34 usr + 0.00 sys = 3.34 CPU) @ 29940.12/s (n=100000)
void: 4 wallclock secs ( 3.29 usr + 0.00 sys = 3.29 CPU) @ 30395.14/s (n=100000)
Rate a_foreach list scalar void
a_foreach 22075/s -- -26% -26% -27%
list 29851/s 35% -- -0% -2%
scalar 29940/s 36% 0% -- -1%
void 30395/s 38% 2% 2% --
There's practically no difference between grep in scalar and list context, while a foreach loop runs 26% slower.
Update: Oops, I'd said foreach was 35% slower. Changed the last paragraph above.
Update: Playing around, if you use grep EXPR, LIST rather than grep BLOCK LIST (i.e. grep $_ == 50, 0..100), that gap grows to 33% (since there's not as much overhead entering and leaving the block). If you switch comparisons from $_ == 50 to /50/ and stick with the BLOCK form, the foreach form is 45% faster.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Re: Checking for value in an array (without FOR)
by Anonymous Monk on Apr 19, 2002 at 20:41 UTC | |
by Fletch (Bishop) on Apr 19, 2002 at 21:05 UTC |