Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

php - Which is better on performance: double quoted strings with variables or single quoted strings with concatenations?

I know that using single quotes around a string in PHP is faster than using the double quotes because PHP doesn't need to check for variable presence in the single quoted string. My question is which will perform better:

A) A double quoted string with variables present:

echo "foo bar $baz";

or

B) Single quoted with a concatenated variable:

echo 'foo bar ' . $baz;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I did a benchmark of this on a blog I was working on a while ago. However, as I've come to realize there are a lot of variables. Chief among them are:

  1. How many concatenations are you doing? Each time you do a concatenation PHP re-parses the entire string (or so I've been told). So 1 concatenation may be faster, but 6 may be considerably slower.
  2. Data type. Though I haven't tested this one myself personally I've been told that the data type being concatenated matters as well, though I'm not sure how much.

Over all I'd say it really isn't that big of a deal for you to actually worry about it. Generally speaking it's only going to make a noticeable difference if you're writing a huge site (think MySpace, Facebook, Flickr, etc) and usually by that point you have so much hardware behind you that the single vs double quotes thing becomes irrelevant again.

Personally I'd say there's far more important things that will impact performance in a much more substantial way (caching, sql optimization, auto loading to prevent unnecessary includes, etc).

I personally choose single quotes nearly every time, but not for speed. I do because I think it's more readable. And that to me is important.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...