Modern PHP, soft skills, productivity and time management.

PHPyths Buster: Single quotes are faster than double quotes



zrzut-ekranu-2016-10-08-o-19-41-13
As you may know, in PHP you can use single and double quotes for strings. These two lines are equal:

<?php
$str1 = "some string";
$str2 = 'some string';

// $str1 === $str2 returns true

The only difference here is handling variables placed inside quotes. Let’s look at this simple example:

<?php
$name = "John";
$str1 = "Hello there $name";
$str2 = 'Hello there $name';

echo $str1; // gives Hello there John
echo $str2; // gives Hello there $name

As you can see in double quotes variables are processed and in single quotes they aren’t.
But which one should I use?

Single quotes must be faster, right?

Some time ago I was using only single quotes for strings in PHP. I thought that if single quotes are just strings and double quotes are processed by PHP then single quotes must be faster. There is no other way – if something isn’t processed then it must be faster than something that is processed. And I was convincing everybody that single quotes are the only proper way to use with strings. I had even an argument about it!

Or maybe…

But some time ago I’ve read somewhere (maybe on facebook?) that double quotes are faster because they are improved all the time, and single quotes are just like they were from the beginning. It sounded reasonable to me, so I just started to use double quotes everywhere.

But one day my coworker asked me why are you using double quotes? and I can’t give him any reasonable answer! Because I don’t check it…

Let’s check it out!

So, today I want to check it and end this topic once and for all. I’ve written the simple script, measure time using `microtime(true);` function and checking the performance of single and double quotes.

<?php

$time = microtime(true);

$loops = 5000000;

for ($i = 0; $i < $loops; $i++) {
    $str = "some string in quotes";
}

echo microtime(true) - $time . PHP_EOL;
$time = microtime(true);

for ($i = 0; $i < $loops; $i++) {
    $str = 'some string in quotes';
}

echo microtime(true) - $time . PHP_EOL;

And the results are clear:
zrzut-ekranu-2016-10-08-o-19-45-57

Yes, it doesn’t matter.

You’re welcome 😉

Don’t forget to check out other PHPhyts!

4 Comments

  1. gunny

    Hmm,

    so what about sprinf vs double quotes when it comes to performance?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2024 Krzych Jończyk

Theme by Anders NorenUp ↑