note 94270 deleted from function.call-user-func-array by danbrown
| From: | danbrown@php.net | Date: | Mon, 26 Oct 2009 16:24:26 +0000 |
| Subject: | note 94270 deleted from function.call-user-func-array by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162119@lists.php.net to get a copy of this message | ||
Note Submitter: prometheus
----
I`m just created an execution time test to compare four different way of method invoking. Used PHP
5.2.6.
Here is the results:
with standard way... called: 1.24909591675
with call_user_func_array()... called: 1.41176390648
with variable method... called: 0.738861083984
with ReflectionClass... called: 2.55120706558
Here is the code:
<?php
class A
{
protected $method;
protected $called = FALSE;
public function __construct()
{
$this->method = 'foo';
}
public function foo($arg)
{
$arg = $arg.'.';
if (!$this->called) echo 'called: ';
$this->called = TRUE;
}
public function t1()
{
$this->called = FALSE;
echo 'with standard way... ';
$s = microtime(TRUE);
for ($i=0; $i<100000; $i++)
{
$this->foo(((string)$i).'bar');
}
$e = microtime(TRUE);
echo $e-$s.'<br>';
}
public function t2()
{
$this->called = FALSE;
echo 'with call_user_func_array()... ';
$s = microtime(TRUE);
for ($i=0; $i<100000; $i++)
{
call_user_func_array(array($this, 'foo'), array(((string)$i).'bar'));
}
$e = microtime(TRUE);
echo $e-$s.'<br>';
}
public function t3()
{
$this->called = FALSE;
echo 'with variable method... ';
$s = microtime(TRUE);
for ($i=0; $i<100000; $i++)
{
$this->{$this->method}(((string)$i).'bar');
}
$e = microtime(TRUE);
echo $e-$s.'<br>';
}
public function t4()
{
$this->called = FALSE;
echo 'with ReflectionClass... ';
$s = microtime(TRUE);
for ($i=0; $i<100000; $i++)
{
$r = new ReflectionClass('A');
$r->getMethod($this->method)->invoke($this, array(((string)$i).'bar'));
unset($r);
}
$e = microtime(TRUE);
echo $e-$s.'<br>';
}
}
$a = new A();
$a->t1();
$a->t2();
$a->t3();
$a->t4();
?>
My conclusion:
Using a normal call is near equivalent to using variable method calling, so I`m going to use much
courageously for all dynamic calling where arguments are fixed.
Then I never use ReflectionXXX for emulate calls. :)
Using call_user_func_array() (or call_user_func) is very expensive. Using call_user_func() is a must
if I use that for calling a static method, otherwise NOT recommended - use variable method calling
instead.
Use call_user_func_array() to call any functions or methods which are parameterized dinamically, but
in design time take a look for that not recommended to use for a "serial calling trip".
It`s a strange how the hell about that but variable method calling looks faster than a normal
call...
(sorry for that english)