我意识到第二种方法避免了函数调用的开销(更新,实际上是一种语言构造),但知道其中一种方法是否比另一种更好会很有趣。我的大部分代码都使用unset(),但最近我在网上找到了一些使用$var = null的体面类。

是否有一个首选的,理由是什么?


当前回答

我为unset和=null创建了一个新的性能测试,因为正如在评论中提到的,这里写的有一个错误(重新创建元素)。 我用的是数组,你们看,现在无所谓了。

<?php
$arr1 = array();
$arr2 = array();
for ($i = 0; $i < 10000000; $i++) {
    $arr1[$i] = 'a';
    $arr2[$i] = 'a';
}

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    $arr1[$i] = null;
}
$elapsed = microtime(true) - $start;

echo 'took '. $elapsed .'seconds<br>';

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    unset($arr2[$i]);
}
$elapsed = microtime(true) - $start;

echo 'took '. $elapsed .'seconds<br>';

但是我只能在PHP 5.5.9服务器上测试它,结果如下: -耗时4.4571571350098秒 -耗时4.4425978660583秒

出于可读性考虑,我更喜欢不设置。

其他回答

我为unset和=null创建了一个新的性能测试,因为正如在评论中提到的,这里写的有一个错误(重新创建元素)。 我用的是数组,你们看,现在无所谓了。

<?php
$arr1 = array();
$arr2 = array();
for ($i = 0; $i < 10000000; $i++) {
    $arr1[$i] = 'a';
    $arr2[$i] = 'a';
}

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    $arr1[$i] = null;
}
$elapsed = microtime(true) - $start;

echo 'took '. $elapsed .'seconds<br>';

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    unset($arr2[$i]);
}
$elapsed = microtime(true) - $start;

echo 'took '. $elapsed .'seconds<br>';

但是我只能在PHP 5.5.9服务器上测试它,结果如下: -耗时4.4571571350098秒 -耗时4.4425978660583秒

出于可读性考虑,我更喜欢不设置。

它对数组元素有影响。

考虑这个例子

$a = array('test' => 1);
$a['test'] = NULL;
echo "Key test ", array_key_exists('test', $a)? "exists": "does not exist";

这里,键“test”仍然存在。然而,在这个例子中

$a = array('test' => 1);
unset($a['test']);
echo "Key test ", array_key_exists('test', $a)? "exists": "does not exist";

密钥不再存在。

PHP 7已经着手解决这类内存管理问题,并将其使用减少到最小。

<?php
  $start = microtime(true);
  for ($i = 0; $i < 10000000; $i++) {
    $a = 'a';
    $a = NULL;
  }
  $elapsed = microtime(true) - $start;

  echo "took $elapsed seconds\r\n";

  $start = microtime(true);
  for ($i = 0; $i < 10000000; $i++) {
     $a = 'a';
     unset($a);
  }
  $elapsed = microtime(true) - $start;

  echo "took $elapsed seconds\r\n";

?>

PHP 7.1输出:

花了0.16778993606567秒 花了0.16630101203918秒

如果没有释放即时内存,则取消设置代码仍然是非常有用的,并且每次在退出方法之前传递代码步骤时都这样做是一个很好的实践。请注意,这不是关于释放即时内存。 直接内存是CPU的,辅助内存是RAM。

这也解决了防止内存泄漏的问题。

请参阅此链接 http://www.hackingwithphp.com/18/1/11/be-wary-of-garbage-collection-part-2

我使用unset已经很长时间了。

更好的做法是在代码中立即取消所有已经作为数组使用的变量。

$data['tesst']='';
$data['test2']='asdadsa';
....
nth.

只需要unset($data);释放所有变量的使用。

请参阅相关主题取消设置

在PHP中取消变量设置有多重要?

(错误)

对于通过引用复制的变量,它的工作方式不同:

$a = 5;
$b = &$a;
unset($b); // just say $b should not point to any variable
print $a; // 5

$a = 5;
$b = &$a;
$b = null; // rewrites value of $b (and $a)
print $a; // nothing, because $a = null