in reply to The fastest way of searching a certain element in an array
This gives the results: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; }, });
So hashes are faster for 101 searches of the same 100_000 element array; crossover is at about 70 searches on my machine.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% --
-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 |