note 100794 modified in function.call-user-func-array by danbrown

From: Date: Sun, 07 Nov 2010 14:01:34 +0000
Subject: note 100794 modified in function.call-user-func-array by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-173830@lists.php.net to get a copy of this message
This function is relatively slow (as of PHP 5.3.3) and if you are calling a method with a known number of parameters it is much faster to call it this way: $class->{$method}($param1, $param2); vs call_user_func_array (array($class, $method), array($param1, $param2)); But if you don't know how many parameters... The wrapper function below is slightly faster, but the problem now is that you are making two function calls. One to the wrapper and one to the function. However, If you are able to take this code out of the function and use it inline it is nearly twice as fast (in most cases) as calling call_user_func_array natively. <?php function wrap_call_user_func_array($c, $a, $p) { switch(count($p)) { case 0: $c->{$a}(); break; case 1: $c->{$a}($p[0]); break; case 2: $c->{$a}($p[0], $p[1]); break; case 3: $c->{$a}($p[0], $p[1], $p[2]); break; case 4: $c->{$a}($p[0], $p[1], $p[2], $p[3]); break; case 5: $c->{$a}($p[0], $p[1], $p[2], $p[3], $p[4]); break; default: call_user_func_array(array($c, $a), $p); break; } } ?> --was-- This function is relatively slow (as of PHP 5.3.3) and if you are calling a method with a known number of parameters it is much faster to call it this way: $class->{$method}($param1, $param2); vs call_user_func_array (array($class, $method), array($param1, $param2)); But if you don't know how many parameters... The wrapper function below is slightly faster, but the problem now is that you are making two function calls. One to the wrapper and one to the function. However, If you are able to take this code out of the function and use it inline it is nearly twice as fast (in most cases) as calling call_user_func_array natively. function wrap_call_user_func_array($c, $a, $p) { switch(count($p)) { case 0: $c->{$a}(); break; case 1: $c->{$a}($p[0]); break; case 2: $c->{$a}($p[0], $p[1]); break; case 3: $c->{$a}($p[0], $p[1], $p[2]); break; case 4: $c->{$a}($p[0], $p[1], $p[2], $p[3]); break; case 5: $c->{$a}($p[0], $p[1], $p[2], $p[3], $p[4]); break; default: call_user_func_array(array($c, $a), $p); break; } } http://php.net/manual/en/function.call-user-func-array.php

« previous php.notes (#173830) next »