Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Finding values position in array

by starbolin (Hermit)
on Apr 14, 2008 at 02:45 UTC ( [id://680197]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://680197]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2024-04-25 02:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found