Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: Map Vs Foreach

by kyle (Abbot)
on Nov 26, 2009 at 13:48 UTC ( #809566=note: print w/replies, xml ) Need Help??

in reply to Map Vs Foreach

Use whichever one most clearly conveys the meaning and intention of the loop in question. I use map for transforming one list to another list. I use grep for filtering items out of a list to produce a new list. I use for to iterate over a list for basically any other reason.

Do not concern yourself with the performance of a looping construct (or anything else) until you've determined that performance is a problem and you've profiled the code and found a particular loop to be the source of the performance problem. Before that, you're making your code more obscure in order to solve a problem that might not even be there.

It's a rare loop whose execution time is influenced by the method of iteration. Look at the examples in this thread. To see differences between map and for, monks are writing loops that do naught more than simple addition. Consider this loop instead:

for my $ip ( @accessors ) { system( 'host', $ip ) == 0 or die "system(host) failed: $?"; }

Would that be faster or slower with map or grep? I doubt it. The call to system is likely taking nearly all of the time, and most of that time is spent waiting on the name server being queried by the 'host' command. Converting this to some other looping construct would have a much greater effect on comprehensibility than on its execution speed and often times clear code is more valuable than fast code anyway.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://809566]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (11)
As of 2017-03-28 11:20 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (330 votes). Check out past polls.