I executed a function several different ways and recorded the run times.
It looks like using a string reference to a regular function is much more efficient.
Summary
- Normal function definition with array_map():
4.001193714
- Lambda definition outside loop with array_map():
10.1116962
- Normal function definition and call:
3.208938837
- Lambda definition and call within loop:
10.32323852
- Lambda definition outside loop:
9.616424465
- Normal function definition and call_user_func():
13.72040915
- Lambda definition outside loop and call_user_func(): 19.98814855
Normal function definition and call
$start_time = microtime(true);
function run_this() {
// Empty function
}
for($i = 0; $i < 5000000; $i++) {
run_this();
}
print "Execution time: " . (microtime(true) - $start_time) . "\n";
- 3.1148610115051
- 3.0175619125366
- 3.5064949989319
- 3.3637712001801
- 3.0420050621033
Average: 3.208938837
Lambda definition and call within loop
$start_time = microtime(true);
for($i = 0; $i < 5000000; $i++) {
$run_this = function () {
// Empty function
};
$run_this();
}
print "Execution time: " . (microtime(true) - $start_time) . "\n";
- 9.857855797
- 10.07680297
- 10.35639596
- 10.51450491
- 10.81063294
Average: 10.32323852
Lambda definition outside loop
$start_time = microtime(true);
$run_this = function () {
// Empty function
};
for($i = 0; $i < 5000000; $i++) {
$run_this();
}
print "Execution time: " . (microtime(true) - $start_time) . "\n";
- 9.098902941
- 9.580584049
- 9.370799065
- 9.90805316
- 10.12378311
Average: 9.616424465
Normal function definition and call_user_func()
$start_time = microtime(true);
function run_this () {
// Empty function
};
for($i = 0; $i < 5000000; $i++) {
call_user_func('run_this');
}
print "Execution time: " . (microtime(true) - $start_time) . "\n";
- 12.80056691
- 13.47905684
- 14.51880193
- 13.79459596
- 14.00902414
Average: 13.72040915
Lambda definition and outside loop and call_user_func()
$start_time = microtime(true);
$run_this = function () {
// Empty function
};
for($i = 0; $i < 5000000; $i++) {
call_user_func($run_this);
}
print "Execution time: " . (microtime(true) - $start_time) . "\n";
- 18.99004483
- 20.08601403
- 20.52800584
- 20.16949892
- 20.16717911
Average: 19.98814855
Normal function definition with array_map()
$arr = array_pad([], 5000, 0);
$start_time = microtime(true);
function run_this () {
// Empty function
};
for($i = 0; $i < 1000; $i++) {
array_map('run_this', $arr);
}
print "Execution time: " . (microtime(true) - $start_time) . "\n";
- 3.727953911
- 4.213405848
- 4.068621874
- 4.180392027
- 3.815594912
Average: 4.001193714
Lambda definition outside loop with array_map()
$arr = array_pad([], 5000, 0);
$start_time = microtime(true);
$run_this = function () {
// Empty function
};
for($i = 0; $i < 1000; $i++) {
array_map($run_this, $arr);
}
print "Execution time: " . (microtime(true) - $start_time) . "\n";
- 9.418456793
- 10.07496095
- 10.1241622
- 10.74794412
- 10.19295692
Average: 10.1116962