note 114872 deleted from language.operators.comparison by crell
| From: | crell@php.net | Date: | Thu, 31 Mar 2022 17:35:57 +0000 |
| Subject: | note 114872 deleted from language.operators.comparison by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217865@lists.php.net to get a copy of this message | ||
Note Submitter: Harry Willis
----
I was interested about the following two uses of the ternary operator (PHP >= 5.3) for using a
"default" value if a variable is not set or evaluates to false:
<?php
(isset($some_variable) && $some_variable) ? $some_variable : 'default_value';
$some_variable ?: 'default_value';
?>
The second is more readable, but will throw an ERR_NOTICE is $some_variable is not set. Of course,
this could be overcome by suppressing the notice using the @ operator.
Performance-wise, though, comparing 1 million iterations of the three statements
(isset($foo) && $foo) ? $foo : ''
($foo) ?: ''
(@$foo) ?: ''
results in the following:
$foo is NOT SET.
[isset] 0.18222403526306
[?:] 0.57496404647827
[@ ?:] 0.64780592918396
$foo is NULL.
[isset] 0.17995285987854
[?:] 0.15304207801819
[@ ?:] 0.20394206047058
$foo is FALSE.
[isset] 0.19388508796692
[?:] 0.15359902381897
[@ ?:] 0.20741701126099
$foo is TRUE.
[isset] 0.17265486717224
[?:] 0.11773896217346
[@ ?:] 0.16193103790283
In other words, using the long-form ternary operator with isset($some_variable) is preferable
overall if $some_variable may not be set.
(error_reporting was set to zero for the benchmark, to avoid printing a million notices...)