想知道以下方法之间的性能有何不同。
// in dependencies.php
$greeting=function(){echo "lambda";};
// in MyClass.php
class MyClass{
function greeting(){echo "class";}
}
// in index.php
include dependencies.php
include MyClass.php
....
// assume using Slim or Laravel routing.
$app->get('/test1', $greeting);
$app->get('/test2', 'MyClass:greeting');
$app->get('/test3', function(){ echo "anonymous"; });
哪种方法是最好的表现?为什么?
答案 0 :(得分:1)
您可以使用它来查看运行每个脚本所需的费用
$start = microtime(true);
$app->get('/test1', $greeting); // replace this one with each of the others
$end = microtime(true);
echo $end-$start; // microseconds
关于记忆:
echo memory_get_usage() . "\n";
$app->get('/test1', $greeting); // replace this one with each of the others
echo memory_get_usage() . "\n";
但我相信你能找到合适的基准测试库。
在我个人看来,班级方法可能会变得最慢。这可能是由于大型__constructor
或__destructor
实施。
答案 1 :(得分:0)
我试过这个
// in dependencies.php
$greeting=function(){echo "lambda";};
$greeting2=function(){echo "lambda2";};
// in MyClass.php
class MyClass{
function greeting(){echo "class";}
}
// in MyClass2.php
class MyClass2{
function greeting(){echo "class2";}
}
// in index.php
include dependencies.php
include MyClass.php
include MyClass2.php
....
// I test this with Slim3 framework
$app->get('/test1', $greeting);
$app->get('/test2', $greeting2);
$app->get('/test3', 'MyClass:greeting');
$app->get('/test4', 'MyClass2:greeting');
$app->get('/test5', function(){ echo "anonymous"; });
The results: test1 0.0031208992004395 test2 1.8119812011719E-5 test3 1.0967254638672E-5 test4 1.0013580322266E-5 test5 1.0967254638672E-5 then i tried different sequences, here the results: test1 0.0039870738983154 test3 1.9073486328125E-5 test2 1.5020370483398E-5 test4 1.0967254638672E-5 test5 1.215934753418E-5 test1 0.004763126373291 test5 2.1934509277344E-5 test3 1.1920928955078E-5 test2 1.0967254638672E-5 test4 1.0013580322266E-5 test5 0.0038559436798096 test1 2.0027160644531E-5 test3 1.2874603271484E-5 test2 1.1920928955078E-5 test4 1.0967254638672E-5
在这个简单的实现中,看起来无论是lambda,object还是匿名都无关紧要。