使用empty()或只使用>;在php中,这是最快的方法


use empty() or just use > in php which is the fastest way

我正在尝试检查变量的值,如果它不是NULL也不是0,则显示其值

$saleprice =  $product["product_details"][0]->salePrice;

我知道使用

if(!empty($saleprice) ) echo " on sale , sale price : $saleprice  ";

if((int)$saleprice > 0) echo " on sale , sale price : $saleprice  ";

会给我同样的结果,但哪一个是最快的?

提前感谢

您可以使用php的微时间函数自己尝试一下

$saleprice = 1;
$start = microtime(true);
if(!empty($saleprice)) echo $saleprice . '<br/>';
echo 'empty: ' . number_format(( microtime(true) - $start), 30) . '<br/>';
$start = microtime(true);
if(!is_null($saleprice))  echo $saleprice . '<br/>';
echo 'is_null: ' . number_format(( microtime(true) - $start), 30) . '<br/>';
$start = microtime(true);
if((int)$saleprice > 0)  echo $saleprice . '<br/>';
echo 'int cast:' . number_format(( microtime(true) - $start), 30) . '<br/>';

在我的本地机器上,它输出以下内容:

空:0.0000121593475341796785000000
is_null:0.00001192092895507812500000000
int cast:0.000010967254638671875000000000

这意味着在$saleprice包含整数的情况下,int强制转换是最快的。如果它包含null,我会得到以下输出:

空:0.000019073486328125000000000
is_null:0.000029087066650390625000000
内部铸造:0.000034093856811523437500000000

在玩了更多之后,我认为可以肯定地说,它在很大程度上取决于您检查的变量实际包含的内容。所以不幸的是,没有一个答案说哪一个是最快的。


更新

不使用任何运算符或语言结构似乎可以获得最佳性能:

$price = null;
$start = microtime(true);
if($price) echo $price . '<br>';
$end = microtime(true);
printf('null: %f' . PHP_EOL, $end - $start);
$price = (int) $price;
$start = microtime(true);
if($price) echo $price . '<br>';
$end = microtime(true);
printf('0: %f' . PHP_EOL, $end - $start);
++$price;
$start = microtime(true);
if ($price) echo $price . '<br>';
$end = microtime(true);
printf('1: %f' . PHP_EOL, $end - $start);

结果是:

null:0.000004
0:0.000001
1:0.000010