go ahead... be a heretic | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Okay, I know that this subject has been talked about many times, but I am here to discuss it again!
As my example, I will use reading in data from GET and POST requests in a CGI script. What am I asking here? Which is best for simple looping: for, foreach, grep, or map? The Code Base
Now, look for the comment in that snippet. This is where each one of the following lines could be inserted to read in the query string and STDIN: Example 1: map { $input{$_} = $q->param($_) } $q->param(); Example 2: grep { $input{$_} = $q->param($_) } $q->param(); Example 3: $input{$_} = $q->param($_) for $q->param(); Example 4: $input{$_} = $q->param($_) foreach $q->param(); Now, the big question. Which one of those four cases above is the most efficient? I am not looking to have "cool looking code". I want to know which one will give the best performance. Myself, I would say that grep is unnecessary because we are not testing for anything and are not (explicitly) assiging the results to an array. Map also places its results into an array, but in this case should provide better performance than grep would. I think the real debate I am having here is between for and foreach. It seems to me that for would do a better job, but am I assuming correctly? Also, perhaps map is a better option than either for or foreach... Wisdom please and thank you! In reply to map, grep, for, foreach by mt2k
|
|