Alex Rivera | Logout

PHP 5 Reflection API performance

Asked 2008-11-16T23:41:58.533
61

I'm currently considering the use of Reflection classes (ReflectionClass and ReflectionMethod mainly) in my own MVC web framework, because I need to automatically instanciate controller classes and invoke their methods without any required configuration ("convention over configuration" approach).

I'm concerned about performance, even though I think that database requests are likely to be bigger bottlenecks than the actual PHP code.

So, I'm wondering if anyone has any good or bad experience with PHP 5 Reflection from a performance point of view.

Besides, I'd be curious to know if any one of the popular PHP frameworks (CI, Cake, Symfony, etc.) actually use Reflection.

Edit
Report

1 Answer

19

Calling a static function 1 million times will cost ~ 0.31 seconds on my machine. When using a ReflectionMethod, it costs ~ 1.82 seconds. That means it is ~ 500% more expensive to use the Reflection API.

This is the code I used by the way:

<?PHP

class test
{
    static function f(){
            return;
    }
}

$s = microtime(true);
for ($i=0; $i<1000000; $i++)
{
    test::f('x');
}
echo ($a=microtime(true) - $s)."\n";

$s = microtime(true);
for ($i=0; $i<1000000; $i++)
{
    $rm = new ReflectionMethod('test', 'f');
    $rm->invokeArgs(null, array('f'));
}

echo ($b=microtime(true) - $s)."\n";

echo 100/$a*$b;

Obviously, the actual impact depends on the number of calls you expect to do

answered 2009-05-30T08:48:42.743

Your Answer