The difference in speed of a loop and first is usually much smaller than you report. In the code below, it's about 3%. What you get in return, though, is readability.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.