public
Created

EventDispatcher benchmarks

  • Download Gist
doDispatcher_benchmarks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
<?php
ini_set('max_execution_time', 86400);
class Timer
{
private $last;
private $marks = array();
 
public function start()
{
$this->last = microtime(true);
}
 
public function mark($name)
{
$this->marks[$name] = microtime(true) - $this->last;
$this->last = microtime(true);
}
 
public function display()
{
foreach ($this->marks as $name => $time) {
echo "$name : $time<br />\n";
}
}
}
 
class Event
{
}
 
function funcHandler(Event $event)
{
}
 
class ExampleListener
{
public function handler(Event $event)
{
}
 
public static function staticHandler(Event $event)
{
}
}
 
class TestDispatcher
{
public function doDispatchOld($listener, Event $event)
{
call_user_func($listener, $event);
}
 
public function doDispatchNew($listener, Event $event)
{
// Check PHP callable format
if (is_array($listener)) {
if (is_object($listener[0])) {
// callable instanciated method
$listener[0]->$listener[1]($event);
} else {
// callable static method
$listener[0]::$listener[1]($event);
}
} else {
// callable function
$listener($event);
}
}
}
 
$event = new Event();
$dispatcher = new TestDispatcher();
 
$k = 1000000;
$timer = new Timer();
$timer->start();
 
// name => callable
$list = array(
'func' => 'funcHandler',
'closure' => function(Event $event){},
'instance' => array(new ExampleListener(), 'handler'),
'static' => array('ExampleListener', 'staticHandler'),
);
 
foreach ($list as $name => $type) {
for ($i = 0; $i < $k; $i++) {
$dispatcher->doDispatchOld($type, $event);
}
$timer->mark("old $name");
for ($i = 0; $i < $k; $i++) {
$dispatcher->doDispatchNew($type, $event);
}
$timer->mark("new $name");
}
 
$timer->display();

FYI: My results

old func : 1.4198741912842
new func : 1.1762499809265
old closure : 1.24285197258
new closure : 1.1229948997498
old instance : 1.3198690414429
new instance : 1.5835971832275
old static : 1.7135539054871
new static : 1.7153100967407

There is definitely a saving, but not with instance callable array($object, 'method') which I find strange.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.