-3

wondering what is the performance different between the following approaches.

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

Which approach is best performance and why?

Zang
  • 3
  • 1
  • 2
    If you're interested in performance: ***benchmark it.*** Likely it makes absolutely no practical difference. – deceze Jan 15 '16 at 10:05

2 Answers2

1

You can use this to see how much it takes to run each script

$start =  microtime(true);
$app->get('/test1', $greeting); // replace this one with each of the others
$end = microtime(true);
echo $end-$start; // microseconds

As for the memory:

echo memory_get_usage() . "\n"; 
$app->get('/test1', $greeting); // replace this one with each of the others
echo memory_get_usage() . "\n"; 

But i'm sure you can find proper benchmarking libraries.

In my personal opinion, the class method can become the slowest. This could be due to large __constructor or __destructor implementations.

Alex Tartan
  • 6,736
  • 10
  • 34
  • 45
0

I had tried this

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

In this simple implementation, seem like it really doesn't matter whether it is lambda, object or anonymous.

Zang
  • 3
  • 1