in reply to How Perl Optimize your code & some code TIPS ;-P
Of these ways to do it, I find number 2 the most readable. you can see immediately what is going on. But you claim that method 3 is the fastest, because you don't have to "rewrite" $var.$var = "foo" ; $var .= "bar" ; # 1 $var = "foo$var" ; # 2 substr($var,0,0) = "foo" ; # 3
For fun, I did a little benchmark:
On a 1.6GHz P4 machine, I got the following results (Perl 5.8.0):#!/usr/bin/perl -w use Benchmark; timethese(1_500_000, { Interpolate => q/$var = "String"; $var = "foo$var";/, Concatenate => q/$var = "String"; $var = "foo" . $var;/, Substr => q/$var = "String"; substr($var, 0, 0) = 'foo'/ });
Perl 5.6.1 and 5.005 give similar results; the substr trick is consistently the slowest.Benchmark: timing 1500000 iterations of Concatenate, Interpolate, Subs +tr... Concatenate: 1 wallclock secs ( 1.56 usr + 0.00 sys = 1.56 CPU) @ 9 +60000.00/s (n=1500000) Interpolate: 1 wallclock secs ( 1.59 usr + 0.00 sys = 1.59 CPU) @ 9 +45812.81/s (n=1500000) Substr: 2 wallclock secs ( 2.07 usr + 0.01 sys = 2.08 CPU) @ 72 +1804.51/s (n=1500000)
So, optimizations can be very useful, but I doubt that it is in this case. I value readability over performance, within reasonable limits. Most of the time, use of another algorithm can yield far better results than micro-optimizations.
Arjen
Update: I made a little mistake in showing the examples. Now, #1 and #2 are IMO equally readable, depending on what you're doing.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: How Perl Optimize your code & some code TIPS ;-P
by autarch (Hermit) on Jan 24, 2003 at 20:34 UTC | |
by Aragorn (Curate) on Jan 25, 2003 at 14:35 UTC | |
by diotalevi (Canon) on Jan 26, 2003 at 16:49 UTC |