in reply to Re: Re: Re: Checking for value in an array (without FOR)
in thread [untitled node, ID 160640]
Meaning:
a_short_circuit_foreach => sub { my $present; foreach( 0..100 ) { if( /0/ ) { $present++; last } } $present },
Which will best case (looking for the first item) be very much faster indeed (1178% than scalar grep), worst case just as bad as the non-short-circuit foreach, and "average" case (in the middle of the list) 12% faster. (All numbers are for the data in question for this benchmark, not in general).
Of course if you're really serious about performance, just use a hash.
#!/usr/bin/perl use Benchmark qw( timethese cmpthese ); my @data = ( 0 .. 100 ); my %cheat; @cheat{ @data } = (1) x @data; my @args = ( -1, { void => sub { grep /50/, @data; 1 }, scalar => sub { my $res = grep /50/, @data }, list => sub { my @res = grep /50/, @data }, a_foreach => sub { my $match; foreach( @data ) { $match++ if /50/ } $match }, a_short_circuit_foreach => sub { my $present; foreach( @data ) { if( /50/ ) { $present++; last } } $present; }, a_hash => sub { exists $cheat{ 50 }; } } ); cmpthese( @args ); exit 0; __END__
Benchmark: running a_foreach, a_hash, a_short_circuit_foreach, list, scalar, void, each for at least 1 CPU seconds...
a_foreach: 1 wallclock secs ( 1.06 usr + 0.00 sys = 1.06 CPU) @ 20286.79/s (n=21504)
a_hash: 1 wallclock secs ( 1.11 usr + 0.01 sys = 1.12 CPU) @ 7080227.68/s (n=7929855)
a_short_circuit_foreach: 2 wallclock secs ( 1.07 usr + 0.00 sys = 1.07 CPU) @ 40193.46/s (n=43007)
list: 1 wallclock secs ( 1.04 usr + 0.00 sys = 1.04 CPU) @ 25845.19/s (n=26879)
scalar: 1 wallclock secs ( 1.02 usr + 0.00 sys = 1.02 CPU) @ 26351.96/s (n=26879)
void: 2 wallclock secs ( 1.04 usr + 0.00 sys = 1.04 CPU) @ 25845.19/s (n=26879)
Rate a_foreach void list scalar a_short_circuit_foreach a_hash
a_foreach 20287/s -- -22% -22% -23% -50% -100%
void 25845/s 27% -- 0% -2% -36% -100%
list 25845/s 27% 0% -- -2% -36% -100%
scalar 26352/s 30% 2% 2% -- -34% -100%
a_short_circuit_foreach 40193/s 98% 56% 56% 53% -- -99%
a_hash 7080228/s 34801% 27295% 27295% 26768% 17515% --
|
|---|