php,speed,comparison,if,then,ternary,longhand,shorthad,optimisation,code - john.mcclumpha

php : PHP speed comparison : longhand if...then vs shorthand ternary operator

Published: 2 yearss ago

After my recent testing of different array methods - I thought it would be good to test out another often used method - the longhand if...then statement versus the shorthand ternary option.

Now the actual statement of if 1 > 0 is hardly rocket science - but serves the basic purpose for this test.

I wrote a short script (similar to the array test one) to go through the statement 10,000,000 times and measure the time taken for each method to execute (source below).

I then ran this test several times on a few different machines to acheive the following results: (note only 1 of these is a 'production' machine - hence the other two seem 'slow')

if then ternary
Server 1 19.7144548893 21.1684539318
39.2457928658 36.9903540611
19.5855939388 21.2798380852
Server 28.4489541054 9.1396198273
8.4465551376 9.1401178837
8.4441728592 9.1415920258
Server 34.6473779678 4.4874329567
3.8062739372 4.0519001484
3.7537870407 4.0154330730

As you can see - the longhand if...then method is quicker - on average only 2.78% faster - not a massive difference over the somewhat 'neater' ternary operator - but on a production server with millions of requests, something that may make quite a big difference. (When was the last time you used a ternary operator to create alternating row colours?).

PHP Source:

<?php

set_time_limit(600);

$items = 10000000;

$array = array();
$start = microtime_float();

for ($i = 1; $i <= $items; $i++)
{
	if(1 > 0) {
		$j++;
	} else {
		$j--;
	}
}

$end = microtime_float();

echo "using <strong>for loop</strong> for " . number_format($items,0) . " items took " . number_format(($end-$start),10) . " seconds.<br />";

unset($array);
$array = array();

$start2 = microtime_float();

for($i = 1; $i <= $items; $i++)
{
	(1 > 0) ? $j++ : $j--;
}

$end2 = microtime_float();

echo "using <strong>ternary operator</strong> for " . number_format($items,0) . " items took " . number_format(($end2-$start2),10) . " seconds.";


function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

?>

recent posts

Follow me on Twitter
Follow me on Facebook

Have you checked out Mister Wong? Simply the best way to manage your bookmarks online:
Mister Wong