开发者

Performance between calling a Class property vs a Class method in PHP?

I know this will not be noticeable at all but just for the sake of learning, is there any overhead of calling class methods over calling a class property like I show in the example below for the $router->controller and $router->action ? Please don't flame me about premature optimization, just trying to learn more.

// Using Clas开发者_Python百科s property
$router = new Router($uri, $uri_route_map);
$router->dispatch($router->controller, $router->action);

// Using Class methods instead
$router = new Router($uri, $uri_route_map);
$router->dispatch($router->controller(), $router->action());


$router->controller is accessing a class property, basically just reading a variable.
$router->controller() is calling a function. Calling a function is bound to have more overhead than reading a variable, especially since the function itself will probably read a variable.


Since you're learning, try it yourself in a timer script to get a rough estimate:

class MyClass
{
    public $property1 = 'a';

    public function method1()
    {
        return $this->property1;
    }
}

$mc = new MyClass();

$start = 0; $end = 0;

// property
$start = microtime(true);
for ($a=0; $a<10000; $a++) {
    $mc->property1; 
}
$end = microtime(true);
echo $end - $start . "<br />\n";

// method
$start = microtime(true);
for ($b=0; $b<10000; $b++) {
    $mc->method1();
}
$end = microtime(true);
echo $end - $start . "<br />\n";

Output:
0.0040628910064697
0.0082359313964844

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜