2016-01-15 28 views
-3

想知道以下方法之間的性能有什麼不同。哪個最好? PHP lambda vs類對象方法

// 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"; }); 

哪種方法最好,爲什麼?

+2

如果您對性能感興趣:***基準測試。***可能它絕對沒有實際區別。 – deceze

回答

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的實現。

+0

...在這樣短的代碼中沒有意義來解決更快或更少的內存。 –

+1

是的,但假設函數*會變得更復雜一些,它可能會變得有用 –

+0

我只是寧願爲較長的代碼做這件事,而不願那麼短。但你是對的。 –

0

我試過這個

​​
 
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 

在這個簡單的實現,看起來像真的不要緊,無論是拉姆達,對象或匿名。

+0

在這個簡短的例子中。更長的代碼會帶來更好的結果。 –

相關問題