mt2k has asked for the wisdom of the Perl Monks concerning the following question:
As my example, I will use reading in data from GET and POST requests in a CGI script.
I will post four example that all produce identical output.
Then I will ask a couple of questions.
What am I asking here? Which is best for simple looping: for, foreach, grep, or map?
The Code Base
#!c:/perl/bin/perl -w use strict; use CGI; my %input; my $q = new CGI; # This is where we will insert the four test # instances. Right under this comment print "Content-type: text/html\n\n"; (my($n,$v) = each %input) { print "$n: $v<br>"; } # code changed at mt2k's request. -kudra Original: # print "$n: $v<br>"; while (my($n,$v) = each %input);
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!
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: map, grep, for, foreach
by rob_au (Abbot) on Jun 06, 2002 at 04:46 UTC | |
by Kanji (Parson) on Jun 06, 2002 at 11:51 UTC | |
by Anonymous Monk on Jun 06, 2002 at 14:28 UTC | |
by Elian (Parson) on Jun 06, 2002 at 18:04 UTC | |
by jsprat (Curate) on Jun 06, 2002 at 18:25 UTC | |
by runrig (Abbot) on Jun 06, 2002 at 17:39 UTC | |
Re: map, grep, for, foreach
by Abigail-II (Bishop) on Jun 06, 2002 at 11:17 UTC | |
Re: map, grep, for, foreach
by Zaxo (Archbishop) on Jun 06, 2002 at 04:59 UTC | |
Re: map, grep, for, foreach
by mt2k (Hermit) on Jun 06, 2002 at 05:00 UTC | |
Re: map, grep, for, foreach
by Aristotle (Chancellor) on Jun 06, 2002 at 05:09 UTC |