简单比较:PHP 函数、闭包的性能

UioSun -
简单比较:PHP 函数、闭包的性能

今天终于忍受不了 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?
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

php介绍

PHP即“超文本预处理器”,是一种通用开源脚本语言。PHP是在服务器端执行的脚本语言,与C语言类似,是常用的网站编程语言。PHP独特的语法混合了C、Java、Perl以及 PHP 自创的语法。利于学习,使用广泛,主要适用于Web开发领域。

Tags 标签

phpstatic内存

扩展阅读

加个好友,技术交流

1628738909466805.jpg