使用PHP的魔术函数__callStatic和正常定义静态函数在性能上有什么区别吗?
示例:
class Welcome{
public static function __callStatic($method, $parameters){
switch ($method) {
case 'functionName1':
// codes for functionName1 goes here
break;
case 'functionName2':
// codes for functionName2 goes here
break;
}
}
}
对比
class Welcome{
public static function functionName1{
//codes for functionName1 goes here
}
public static function functionName1{
//codes for functionName1 goes here
}
}
最佳答案
如果您只是谈论速度,那么这很容易测试:
class Testing
{
private static $x = 0;
public static function f1()
{
self::$x++;
}
public static function f2()
{
self::$x++;
}
public static function __callStatic($method, $params)
{
switch ($method) {
case 'f3':
self::$x++;
break;
case 'f4':
self::$x++;
break;
}
}
}
$start = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
Testing::f1();
Testing::f2();
}
$totalForStaticMethods = microtime(true) - $start;
$start = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
Testing::f3();
Testing::f4();
}
$totalForCallStatic = microtime(true) - $start;
printf(
"static method: %.3f\n__callStatic: %.3f\n",
$totalForStaticMethods,
$totalForCallStatic
);
我得到static method: 0.187
和__callStatic: 0.812
,因此定义实际方法的速度快了 4 倍以上。
我还想说使用__callStatic
除非你有充分的理由,否则这种风格很糟糕。这使得跟踪代码变得更加困难,并且 IDE 更难提供自动完成功能。也就是说,在很多情况下这是值得的。
关于php - PHP 的 __callStatic 与静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31155382/