[LA.pm] Double versus single quotes

Benjamin J. Tilly ben_tilly at operamail.com
Tue Nov 25 16:51:23 CST 2003


"John W. Palmieri" <john at mediaonfire.com> wrote:
> 25 November 2003
> 
> Hi:
> 
> A technical question for anyone who has a spare minute:
> 
> When I'm using strings in Perl I try to use single quotes 
> for static strings (e.g., 'This string is static') since I 
> figure that the interpreter won't have to work as hard as it 
> doesn't have to look for variables, escapes, etc. (e.g., 
> "This is a $dynamic string\n"). I have no evidence that this 
> makes a difference, but it seems reasonable. Is it?

It is reasonable, true, but is such a small difference that I
will probably spend more time writing this email than the
difference between the two for parsing every invocation of
every Perl program that you will ever write.  See
http://www.perlmonks.org/index.pl?node_id=53630 for details.

Insert usual lecture on premature optimization.  If you have
never seen it, then http://www.stevemcconnell.com/cctune.htm
gives a decent version.

> Also, when building an output string I'll tend to use long 
> static strings followed by the dot (.) concatenator for 
> inserting variables using the same reasoning. I'm asking 
> this question since I've come around that this may not be 
> the most efficient since with every concatenation it may 
> have to do exec a bunch of constructors and copies?

I won't insert the usual lecture on premature optimization
because something like this can be an issue in other
languages.  For instance in Java, JavaScript, C++, etc it
can be very slow to create a large string by incrementally
appending many small strings to a growing one.  That is,
their equivalents of the following is slow (ie it scales
quadratically with the number of strings):

  my $hello = "";
  for (1..200_000) {
    $hello .= "Hello, world\n";
  }

However the Perl interpreter is smart about this.  It will
pre-buffer the end of the string and only have to
reallocate at need with a dynamically sized buffer.
Therefore the amortized cost of appending another small
string is constant.  So the above piece of code is not a
performance issue in Perl.

What this means is that worrying about the cost of doing a
ton of constructors and copies with string manipulation is
entirely a non-issue in Perl although it can become one in
other languages.

However in this specific instance, interpolation works
EXACTLY the same way under the hood as concatenation.  Given
that interpolation is easier to read, there is no excuse not
to use it.  (If you really want to focus on trivial
differences, then focus on all of the punctuation that Perl
will wind up not having to parse.)

> Anyone have thoughts on these (small) issues?

I just gave you the basic information.

The bigger issue is that you need to stop worrying about micro
optimizations and worry about real programming problems.

Cheers,
Ben



More information about the Losangeles-pm mailing list