doupao2277 2015-07-01 07:43
浏览 46
已采纳

__callStatic vs PHP的静态函数

Is there are any performance difference between using PHP's magic function __callStatic and defining static function normally.

Example:

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;
   }
 }

}

vs

class Welcome{

 public static function functionName1{
   //codes for functionName1 goes here
 }
 public static function functionName1{
   //codes for functionName1 goes here
 }

}
  • 写回答

1条回答 默认 最新

  • doutao6380 2015-07-01 08:07
    关注

    If you're just talking about speed, this is easy enough to test:

    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
    __callStatic: %.3f
    ",
        $totalForStaticMethods,
        $totalForCallStatic
    );
    

    I get static method: 0.187 and __callStatic: 0.812, so defining actual methods is over 4 times faster.

    I would also say that using __callStatic is bad style unless you have a good reason for it. It makes it harder to trace code, and IDEs have a harder time providing auto-complete features. That said, there are plenty of cases where it's worth it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作