I was challenged in my last post to deeper check performance of strings. I think it will be quite interesting to test out some cases and say which way of using strings is the best.
In this post, I will check several string usages in PHP 5.6 and PHP 7.
To simplify testing I created a simple function which gets 2 arguments: an array of callable functions to compare (as many as you want) with names to display in summary, and a number of loops to test the function…
As you may know, in PHP you can use single and double quotes for strings. These two lines are equal:
$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:
$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?