【问题标题】:use empty() or just use > in php which is the fastest way使用 empty() 或只在 php 中使用 > 这是最快的方法
【发布时间】:2015-06-26 18:29:07
【问题描述】:

我正在尝试检查一个变量的值,如果它不是 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  ";

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

提前谢谢你

【问题讨论】:

  • 如果 $product["product_details"][0]->salePrice 真的返回 NULL 那么你可以使用 if($saleprice)
  • 我更新了我的问题
  • 哪个最快有关系吗?我会选择更具可读性的东西。 en.wikipedia.org/wiki/Program_optimization#When_to_optimize
  • 列出的方法都不是函数,也没有可比性。您还忘记了=====!(类型和值检查)。另外:微优化是万恶之源。只要know what the pitfalls are,你就没事了
  • @Nassim:您希望$saleprice 为!= 0 或NULL,即:您需要它是一个truthy 值,在这种情况下:@987654330无论如何,@ 就是你所需要的

标签: php optimization


【解决方案1】:

您可以使用 php 的 microtime 函数自己尝试一下:

$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.000012159347534179687500000000
is_null: 0.000011920928955078125000000000
诠释:0.000010967254638671875000000000

意思是如果$saleprice 包含一个整数,int 转换是最快的。如果它包含null,我会得到以下输出:

空:0.000019073486328125000000000000
is_null: 0.000029087066650390625000000000
诠释: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);

结果是:

空值:0.000004
0: 0.000001
1:0.000010

【讨论】:

  • @Nassim:您想检查$saleprice 是否既不是null 也不是0。这两个值都计算为false,所以为什么要使用运算符或语言结构:if ($saleprice) 会做,而且它似乎胜过其他任何东西:null: 0.000004 (int) 0: 0.000001 (int) 1: 0.000010 代码if ($saleprice) echo $saleprice . '&lt;br&gt;'; timed
  • @EliasVanOotegem 谢谢,我会更新答案,希望treegarden 会接受我的更新
  • @Nassim:更改了您的编辑。最好保留原来的答案,然后在下面添加更多信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 2015-09-25
  • 2016-08-21
  • 1970-01-01
相关资源
最近更新 更多