我以几种不同的方式执行了一个函数并记录了运行时间。
看起来使用对常规函数的字符串引用效率更高。
总结
- 使用 array_map() 的普通函数定义:
4.001193714
- 使用 array_map() 在循环外定义 Lambda:
10.1116962
- 普通函数定义和调用:
3.208938837
- Lambda 定义和循环内调用:
10.32323852
- 循环外的 Lambda 定义:
9.616424465
- 普通函数定义和call_user_func():
13.72040915
- 循环外的 Lambda 定义和 call_user_func(): 19.98814855
普通函数定义和调用
$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
平均:3.208938837
Lambda 定义和循环内调用
$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
平均:10.32323852
循环外的 Lambda 定义
$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
平均:9.616424465
普通函数定义和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
平均:13.72040915
Lambda 定义和外部循环以及 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
平均:19.98814855
使用 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
平均:4.001193714
使用 array_map() 在循环外定义 Lambda
$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
平均:10.1116962