in reply to The fastest way of searching a certain element in an array

Nice comparison. Your problem is basically testing for set membership, and that is often done using a hash if there are lots of searches:
use Benchmark qw(:all) ; my $test_element = 42_000; my @a = (1..100_000); my $count = 20; cmpthese($count, { 'hash' => sub { my %seen; undef( @seen{ @a } ); # a trick I learned from t +illy my $found = 0; for my $iter (10_000..10_100) { # 101 searches $found = 1 unless exists $seen{ $iter }; } return $found; }, 'for' => sub { my $found = 0; for my $iter (10_000..10_100) { # 101 searches foreach (@a) { $found = 1 and last if $iter == $_; } } return $found; }, });
This gives the results:
Benchmark: timing 20 iterations of for, hash... for: 16 wallclock secs (15.67 usr + 0.00 sys = 15.67 CPU) @ 1 +.28/s (n=20) hash: 8 wallclock secs ( 8.57 usr + 0.04 sys = 8.61 CPU) @ 2 +.32/s (n=20) Rate for hash for 1.28/s -- -45% hash 2.32/s 82% --
So hashes are faster for 101 searches of the same 100_000 element array; crossover is at about 70 searches on my machine.

-Mark

Replies are listed 'Best First'.
Re: Re: The fastest way of searching a certain element in an array
by ccn (Vicar) on Apr 10, 2004 at 18:28 UTC
    Yes, of course. The hash is fastest if a search is often. Your numbers are interesting.
    Update: these numbers help to understand what does the often mean