Re: Ternary operator performance improvements
| From: | Ilia Alshanetsky | Date: | Mon, 17 Oct 2011 12:52:21 +0000 |
| Subject: | Re: Ternary operator performance improvements | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-55839@lists.php.net to get a copy of this message | ||
Seems like a good patch, +1 from me on inclusion into 5.4/HEAD.
On Fri, Oct 14, 2011 at 2:08 PM, Arnaud Le Blanc <arnaud.lb@gmail.com> wrote:
> 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,
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>