#! /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 outside 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% --