Skip to content

Instantly share code, notes, and snippets.

@kelunik
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kelunik/5534cc5b76bfa22263a9 to your computer and use it in GitHub Desktop.
Save kelunik/5534cc5b76bfa22263a9 to your computer and use it in GitHub Desktop.
<?php
chdir(__DIR__);
error_reporting(E_ALL);
class BenchCase {
private $callable;
public function __construct (callable $callable) {
$this->callable = $callable;
}
public function bench () {
$time = PHP_INT_MAX;
for ($x = 0; $x < 10; $x++) {
$start = microtime(1);
for ($i = 0; $i < 1000000; $i++) {
($this->callable)();
}
$time = min($time, microtime(1) - $start);
}
return $time;
}
protected function onData ($data) {
// empty on purpose!
}
}
class AnonymousFunctionCase extends BenchCase {
public function __construct() {
parent::__construct(function($data) {
$this->onData($data);
});
}
}
class ReflectionCase extends BenchCase {
public function __construct() {
$reflection = new ReflectionClass(self::class);
$closure = $reflection->getMethod("onData")->getClosure($this);
parent::__construct($closure);
}
}
Amp\run(function () {
$test = new AnonymousFunctionCase;
printf("anon function: %f\n", $test->bench());
$test = new ReflectionCase;
printf("reflection: %f\n", $test->bench());
});
@rdlowrey
Copy link

rdlowrey commented Aug 3, 2015

<?php

class Foo {
    private $privateCallable;
    function __construct() {
        $this->privateCallable = (new \ReflectionClass($this))->getMethod("bar")->getClosure($this);
    }
    private function bar() {
        return 42;
    }
    function getPrivate() {
        return $this->privateCallable;
    }
    function getPublic() {
        return function() {
            return $this->bar();
        };
    }
}

$foo = new Foo;

$callable = $foo->getPrivate();
$timeStart = microtime(1);
for ($i=0; $i<100000; $i++) {
    $callable();
}
var_dump(microtime(1) - $timeStart);

$callable = $foo->getPublic();
$timeStart = microtime(1);
for ($i=0; $i<100000; $i++) {
    $callable();
}
var_dump(microtime(1) - $timeStart);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment