Skip to content

Instantly share code, notes, and snippets.

@asaokamei
Last active March 15, 2016 04: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 asaokamei/6cef9202b63bca4bf192 to your computer and use it in GitHub Desktop.
Save asaokamei/6cef9202b63bca4bf192 to your computer and use it in GitHub Desktop.
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

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