Hashing is useful if you're going to search the same array repeatedly many times. Special care is needed if the values in the original array are not unique (not handled in my example).
#! /usr/bin/perl use warnings; use strict; use List::Util qw{ first }; use Test::More; use Benchmark qw{ cmpthese }; my @haystack = 1 .. 1_000_000; my $needle = 999_000; sub frst { my $w = shift; first { $haystack[$_] == $w } 0 .. $#haystack } sub loop { my $w = shift; for my $i (0 .. $#haystack) { return $i if $haystack[$i] == $w; } } { my %h; sub hash { my $w = shift; @h{@haystack} = 0 .. $#haystack unless %h; # This could go out +side the sub, too. $h{$w} } } cmpthese(-3, { frst => sub { frst($needle) }, loop => sub { loop($needle) }, hash => sub { hash($needle) }, }); is(frst($needle), loop($needle), 'first == loop'); is(frst($needle), hash($needle), 'first == hash'); done_testing(2);
Rate frst loop hash frst 19.6/s -- -3% -100% loop 20.2/s 3% -- -100% hash 4074780/s 20814138% 20170060% --
In reply to Re: How do I find the index of a specific array value?
by choroba
in thread How do I find the index of a specific array value?
by SM177Y
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |