jpfarmer has asked for the wisdom of the Perl Monks concerning the following question:
I'm using CGI.pm to write a CGI script and out of necessity, I have to do a lot of printing and I'm unsure of the best way to write it from a efficiency or style standpoint.
I ran a benchmark (output to the console, not to a browser) using this code:
use Benchmark qw/cmpthese/; use CGI; our $cgi = new CGI; cmpthese 5000,{ per_line => <<'EOFCODE', # Loop 10,000 times at 1 output per loop for a total of # 10,000 outputs. for (my $i = 0, $i == 10000, $i++){ print $cgi->p('This is a test.'); } EOFCODE # The following l concat => <<'EOFCODE', # Loop 1,000 times at 10 outputs per loop for a total of # 10,000 outputs. for (my $i = 0, $i == 1000, $i++){ print $cgi->p('This is a test.').$cgi->p('This is a test.'). $cgi->p('This is a test.').$cgi->p('This is a test.'). $cgi->p('This is a test.').$cgi->p('This is a test.'). $cgi->p('This is a test.').$cgi->p('This is a test.'). $cgi->p('This is a test.').$cgi->p('This is a test.'); } EOFCODE comma => <<'EOFCODE', # Loop 1,000 times at 10 outputs per loop for a total of # 10,000 outputs. for (my $i = 0, $i == 1000, $i++){ print $cgi->p('This is a test.'), $cgi->p('This is a test.'), $cgi->p('This is a test.'), $cgi->p('This is a test.'), $cgi->p('This is a test.'), $cgi->p('This is a test.'), $cgi->p('This is a test.'), $cgi->p('This is a test.'), $cgi->p('This is a test.'), $cgi->p('This is a test.'); } EOFCODE };
And got these results:
Rate concat comma per_line concat 747/s -- -0% -88% comma 749/s 0% -- -88% per_line 6098/s 716% 715% --
It would seem, from this, that printing one line at a time is clearly most efficient, even though it had to loop through 10x more times. However, I don't know if that is conclusive, or if code efficency alone should dictate the style the program is written in.
I have come for guidance: should I make each of my print statements its own line, should I join them with commas, or should I concatenate them as strings? I'm also willing to accept that it doesn't really matter at all. Thanks in advance.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Proper way to print a large number of strings
by FamousLongAgo (Friar) on Jan 07, 2003 at 15:09 UTC | |
|
Re: Proper way to print a large number of strings
by Aristotle (Chancellor) on Jan 07, 2003 at 15:47 UTC | |
|
Re: Proper way to print a large number of strings
by hardburn (Abbot) on Jan 07, 2003 at 14:55 UTC | |
by jpfarmer (Pilgrim) on Jan 07, 2003 at 15:04 UTC | |
by grinder (Bishop) on Jan 07, 2003 at 16:49 UTC | |
by Aristotle (Chancellor) on Jan 11, 2003 at 16:39 UTC | |
by Fletch (Bishop) on Jan 07, 2003 at 15:30 UTC |