php 文档中的示例Closure::bind
包括static
关于匿名函数声明。为什么?如果删除的话我找不到区别。
with:
class A {
private static $sfoo = 1;
}
$cl1 = static function() { // notice the "static"
return self::$sfoo;
};
$bcl1 = Closure::bind($cl1, null, 'A');
echo $bcl1(); // output: 1
without:
class A {
private static $sfoo = 1;
}
$cl1 = function() {
return self::$sfoo;
};
$bcl1 = Closure::bind($cl1, null, 'A');
echo $bcl1(); // output: 1
我不敢苟同。确实,很多时候这并不重要。但有时这很重要一大堆.
持有引用的闭包$this
可能会阻止该对象的垃圾收集,这反过来也可能会显着影响性能。这是一个真正产生巨大差异的例子:
class LargeObject {
protected $array;
public function __construct() {
$this->array = array_fill(0, 2000, 17);
}
public function getItemProcessor(): Closure {
// Try with and without 'static' here
return static function () {
// do some processing unrelated to $this
};
}
}
$start = microtime(true);
$processors = [];
for ($i = 0; $i < 2000; $i++) {
$lo = new LargeObject();
$processors[] = $lo->getItemProcessor();
}
$memory = memory_get_usage() >> 20;
$time = (microtime(true) - $start) * 1000;
printf("This took %dms and %dMB of memory\n", $time, $memory);
这是正常关闭的输出:
This took 55ms and 134MB of memory
这是静态闭包的输出:
This took 22ms and 1MB of memory
我在 Debian Buster 上使用 PHP 7.3.19 进行了测试,所以 YMMV。显然,这是一个专门构建的示例来展示差异。但类似的事情在实际应用中也可能发生。我开始使用 Slevomat 的SlevomatCodingStandard.Functions.StaticClosure https://github.com/slevomat/coding-standardsniff 提醒我始终使用静态闭包。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)