News Archive
PhpRiot Newsletter
Your Email Address:

More information

The PHP Ternary Operator: Fast or not?

Note: This article was originally published at Planet PHP on 16 July 2011.
Planet PHP

People like micro-optimizations. They are easy to understand, easy to apply... and useless. But some time ago, while reviewing pull requests for Twig, I read an interesting discussion about the performance of the ternary operator in PHP (thanks to @nikic for the investigation).

Do you know which following snippet is the fastest (of course, they do exactly the same)?

// snippet 1 $tmp = isset($context['test']) ? $context['test'] : ''; A // snippet 2 if (isset($context['test'])) { $tmp = $context['test']; } else { $tmp = ''; } A

The right answer is: it depends. Most of the time, they are about the same speed and you don't need to care. But if $context['test'] contains a large amount of data, snippet 2 is much faster than snippet 1.

Here is the code I have used to test different scenarii:

$context = array('test' = true); A // optionally fill-in the test value with lots of data for ($i = 0; $i 100000; $i++) { $context['test'][$i] = $i; } // you can also just create a big string // $context = str_repeat(' ', 1000000); A // benchmark $time = microtime(true); for ($i = 0; $i 100; $i++) { // the snippet of code to benchmark $tmp = isset($context['test']) ? $context['test'] : ''; } printf("TIME: %0.2d\n", (microtime(true) - $time) * 1000); A

Note that the absolute performance numbers are meaningless here. We just want to compare the speed between different snippets.

On my laptop, snippet 1 takes more than two seconds, whereas snippet 2 takes about 0.05ms. That's a big difference! But if the variable to te

Truncated by Planet PHP, read more at the original (another 2124 bytes)