Speed of Various PHP Quoting Options

I was discussing the speed of various quoting options in PHP with a co-worker. He thought that variables inside of double quotes (“$a plus $b”) were faster than concatenated variables ($a . ' plus ' . $b), but I've heard the opposite. I wanted to try those variations to see which was actually faster on my local machine and how much of a difference there was.

In actual coding practice I prefer whichever format looks the best and is the easiest to understand when reviewing that code; speed be damned.

I wrote the following quick test script. It's devoid of comments because I didn't want those to effect the results. There are obviously lots of other factors that could effect these results as well. I also tried test 2 before test 1 to see if order mattered. The results were ultimately the same.

<?php

	// Test the speed of certain actions
	
	$val = "0 : 0";
	$a = 'a';
	$b = 'b';
	
	DEFINE('LOOPS', 100000000);
	
	$start = time();
	for($i=1; $i<=LOOPS; $i++) {
		$val = "$a : $b";
	}
	$end = time();
	$total = $end - $start;
	echo "Total 1: $total ($start : $end)\n";

	$start = time();
	for($i=1; $i<=LOOPS; $i++) {
		$val = $a . ' : ' . $b;
	}
	$end = time();
	$total = $end - $start;
	echo "Total 2: $total ($start : $end)\n";

?>

Here are the results on my laptop.

Total 1: 111 (1258827927 : 1258828038)
Total 2: 98 (1258828038 : 1258828136)

In this situation concatenation was a tiny fraction faster than double quotes. But, the difference is so minimal that it's hardly worth noting.

comments powered by Disqus
php/speed_of_various_quoting_options.txt · Last modified: 2020/06/01 22:53 (external edit)