关于php:简单比较PHP-函数闭包的性能

0次阅读

共计 1138 个字符,预计需要花费 3 分钟才能阅读完成。

明天终于忍耐不了 EA 插件的某个提醒了:

  • [EA] This closure can be declared as static (better scoping; in some cases can improve performance).

脑海第一反馈是:Static 不是会占用内存吗?它们的效率如何呢?

棘手搜到了这位老哥的代码片段:

PHP performance: function vs closures – Gist

create_function() 的代码曾经被官网废除了,棘手批改:

<?php  
$iter = 10000000;  
  
$start = microtime(true);  
function funcK($item) {return $item;};  
for ($i = 0; $i < $iter; $i++)  
{funcK($i);  
}  
$end = microtime(true) - $start;  
echo "Defined function:".PHP_EOL;  
echo "$end seconds\n".PHP_EOL;  
  
$start = microtime(true);  
$fn = function($item) {return $item;};  
for ($i = 0; $i < $iter; $i++)  
{$fn($i);  
}  
$end = microtime(true) - $start;  
unset($fn);  
echo "Closure function:".PHP_EOL;  
echo "$end seconds\n".PHP_EOL;  
  
$start = microtime(true);  
$fn = static function($item) {return $item;};  
for ($i = 0; $i < $iter; $i++)  
{$fn($i);  
}  
$end = microtime(true) - $start;  
echo "Closure static function:".PHP_EOL;  
echo "$end seconds\n".PHP_EOL;

棘手跑一下:

Defined function:
0.27448701858521 seconds

Closure function:
0.33962607383728 seconds

Closure static function:
0.33882212638855 seconds

多棘手几次——后果基本一致。

通过一溜烟的棘手操作,根本确定这俩性能很靠近。

当然,PHP8.1 时,对定义好的 Function 调用效率依然超过其余两位。


最初,各语言在解决面向对象时,其 static 基本上是基于 Class 而占用内存,当咱们应用命名空间和懒加载时,实践上将躲避 过多的 static 引入 问题。

能够参考这里:

Does using static methods and properties in PHP use less memory?

正文完
 0