Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
performance measurement of closure and class construction.
<?php
// Here your code !
function runIt($closure, $title)
{
$n = 1000000;
$time1 = microtime(true);
$closure($n);
$time2 = microtime(true);
echo sprintf("%12s: %6.2f msec\n", $title, ($time2 - $time1) * 1000);
};
$do_closure = function ($n = 100)
{
for($i = 0; $i < $n; $i++) {
$s = function() use($i) {return 'hi';};
}
};
class sample {
function __invoke() {
return 'hi';
}
}
$do_class = function ($n = 100)
{
for($i = 0; $i < $n; $i++) {
$s = new sample($i);
}
};
$do_clone = function ($n = 100)
{
$s0 = new sample();
for($i = 0; $i < $n; $i++) {
$s = clone $s0;
}
};
function test_func($i) {
return 'hi';
}
$do_function = function ($n = 100)
{
for($i = 0; $i < $n; $i++) {
$s = test_func($i);
}
};
runIt($do_function, 'function');runIt($do_closure, 'closure');
runIt($do_class, 'new class');
runIt($do_clone, 'clone obj');
@asaokamei
Copy link
Author

asaokamei commented Mar 14, 2016

result (on Mac mini, Core i7, PHP5.6.16)

    function: 1175.23  msec
     closure: 482.19  msec
   new class: 428.53  msec
   clone obj: 354.40  msec

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