http://qs321.pair.com?node_id=809566


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.