Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sumonst21/099ec50363dd30b1e9c22ee5e4686fe0 to your computer and use it in GitHub Desktop.
Save sumonst21/099ec50363dd30b1e9c22ee5e4686fe0 to your computer and use it in GitHub Desktop.
PHP quotes and concatenation style rules for "highest code performance"

PHP quotes and concatenation style rules for "highest code performance"

The problem

PHP has many ways to concatenate strings, and many ways to expand variables inside strings. But which is the fastest?

The solution

the rule is simple, use double quotes for concatenation and use curly braces for variable expansion. example:

$var = 'foo';
echo "This is a {$var} notation";

for more details, see the rules section below and the tests section below that.

The rules

  1. Always use double-quoted strings for concatenation, because it's the fastest method. The only exception is when you're concatenating a variable with a literal string that has no variables in it, then you can use single-quoted strings for a tiny bit of extra performance.
  2. Put your variables in "This is a {$variable} notation", because it's the fastest method which still allows complex expansions like "This {$var['foo']} is {$obj->awesome()}!". You cannot do that with the "${var}" style.
  3. Feel free to use single-quoted strings for TOTALLY literal strings such as array keys/values, variable values, etc, since they are a TINY bit faster when you want literal non-parsed strings. But I had to do 1 billion iterations to find a 1.55% measurable difference. So the only real reason I'd consider using single-quoted strings for my literals is for code cleanliness, to make it super clear that the string is literal.
  4. If you think another method such as sprintf() or 'this'.$var.'style' is more readable, and you don't care about maximizing performance, then feel free to use whatever concatenation method you prefer!

The tests

refer to the source of tests results here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment