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:
Yes, it doesn’t matter.
You’re welcome 😉
Don’t forget to check out other PHPhyts!
- PHPyths Buster: A great string performance test! (updated)
- PHPyths Buster: Single quotes are faster than double quotes
- PHPyths Buster: Annotations
- PHPyths Buster: End of the project
- PHPyths Buster: Displaying reminders
- PHPyths Buster: Evernote SDK [update]
- PHPyths Buster: Basic application
- PHPyths Buster: Hello World!
- PHPyths Buster: Project environment
- PHPyths Buster: The Project
Hmm,
so what about sprinf vs double quotes when it comes to performance?
There are many options to check, e.g. PHP5 vs PHP7, sprintf vs concatenation with `.`. This is very good topic to discover so I have a topic for the next post, thanks 😀
Aaaand here it is 🙂 http://jonczyk.me/2016/10/23/phpyths-buster-great-string-performance-test/
Here is good explanation why: https://nikic.github.io/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html