doupao2277 2015-06-30 23: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 00: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.

    展开全部

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部