Ternary operator performance improvements

From: Date: Fri, 14 Oct 2011 18:08:56 +0000
Subject: Ternary operator performance improvements
Groups: php.internals 
Request: Send a blank email to internals+get-55805@lists.php.net to get a copy of this message
Hi, I've already posted this patch and it has since been reviewed and improved. I'm re-posting it for discussion before eventually commiting it. The ternary operator always copies its second or third operand, which is very slow compared to an if/else when the operand is an array for example: $a = range(0,9); // this takes 0.3 seconds here: for ($i = 0; $i < 5000000; ++$i) { if (true) { $b = $a; } else { $b = $a; } } // this takes 3.8 seconds: for ($i = 0; $i < 5000000; ++$i) { $b = true ? $a : $a; } I've tried to reduce the performance hit by avoiding the copy when possible (patch attached). Benchmark: Without patch: (the numbers are the time taken to run the code a certain amount of times) $int = 0; $ary = array(1,2,3,4,5,6,7,8,9); true ? 1 : 0 0.124 true ? 1+0 : 0 0.109 true ? $ary : 0 2.020 ! true ? $int : 0 0.103 true ? ${'ary'} : 0 2.290 ! true ?: 0 0.091 1+0 ?: 0 0.086 $ary ?: 0 2.151 ! ${'var'} ?: 0 2.317 ! With patch: true ? 1 : 0 0.124 true ? 1+0 : 0 0.195 true ? $ary : 0 0.103 true ? $int : 0 0.089 true ? ${'ary'} : 0 0.103 true ?: 0 0.086 1+0 ?: 0 0.159 $cv ?: 0 0.090 ${'var'} ?: 0 0.089 The array copying overhead is eliminated. There is however a slowdown in some of the cases, but overall there is no completely unexpected performance hit as it is the case currently. What do you think ? Is there any objection ? Best regards,

Attachment: [text/x-patch] ternary-improvements.diff.txt
« previous php.internals (#55805) next »