in reply to Finding values position in array

Define quicker. foreach() is quicker but mapping to a hash allows for multiple lookups and is less typing.

#!/usr/bin/perl use Benchmark 'cmpthese'; use warnings; @array = ( 'a'..'z' ); $value = 'z'; my $res; my $position; print "for(): ".traditional()."\tforeach: ".for_each()."\tmap: ".mapto +hash()."\n"; cmpthese ( 10000, { for_loop => '$res = traditional()', map => '$res = maptohash()', for_each => '$res = for_each()', } ); sub traditional{ for ($position=0; $position <= $#array; $position++) { last if ($array[$position] eq $value); } return $position; } sub for_each{ for our $position ( 0..$#array ) { last if ($array[$position] eq $value) ; } return $position; } sub maptohash{ %indexed = map{ $array[$_], $_ } (0..$#array); return $indexed{$value}; } %perl foo.pl [7:41pm] for(): 25 foreach: 25 map: 25 Rate map for_loop for_each map 5100/s -- -40% -72% for_loop 8477/s 66% -- -53% for_each 18028/s 254% 113% --


s//----->\t/;$~="JAPH";s//\r<$~~/;{s|~$~-|-~$~|||s |-$~~|$~~-|||s,<$~~,<~$~,,s,~$~>,$~~>,, $|=1,select$,,$,,$,,1e-1;print;redo}

Replies are listed 'Best First'.
Re^2: Finding values position in array
by GrandFather (Saint) on Apr 14, 2008 at 03:18 UTC

    The issue is more about appropriate tools for the job than hammering various shaped pegs into whatever hole you have.

    • use grep to get an output list that is a subset of an input list
    • use map to transform an input list into an output list
    • use for to iterate over a list (and almost never use the C version of for)
    • use a hash to look up keyed data quickly
    • use an array to lookup indexed data quickly
    • because hash keys are unique a hash is a good tool for finding unique strings in a bag of strings

    Perl is environmentally friendly - it saves trees