Decorator or Subclassing?

Using anonymous functions in PHP is very nice to implement a decorator, but what about performance? Results:
  • Subclassing is 40 percent faster than using a decorator
  • Subclassing might require a bit more code

Here is the code:

class App {
public static function route($pattern, $callback, $args) {
// evaluate $pattern ...
call_user_func_array($callback, $args);
}
}

class AppJson extends App {
public static function route($pattern, $callback, $args) {
// evaluate $pattern ...
$str = json_encode(call_user_func_array($callback, $args));
}
}


$start = microtime(true);
for ($i=0; $i<10000; $i++) {
AppJson::route('/json/range', 'range', [0,10]);
}
echo ' '.(microtime(true)-$start); // 0.1058s


$json = function ($func) {
return function() use (&$func) {
$str = json_encode(call_user_func_array($func, func_get_args()));
};
};

$start = microtime(true);
for ($i=0; $i<10000; $i++) {
App::route('/json/range', $json('range'), [0,10]);
}
echo ' '.(microtime(true)-$start); // 0.1763s

Comments

Popular posts from this blog

How to show only month and year fields in android Date-picker?

How to construct a B+ tree with example

Conflict Serializability in database