导语
时间飞速流逝,转眼已经过去了3年,这几年科技在快速发展,PHP也来到了8.0.10
版本。
回望这几年,大数据时代悄然降临,面对海量的数据,我们迫切的需要更为快速的运算性能;基础硬件的升级、软件算法的迭代,这些都是必不可少的部分。
编程语言也在不断进化着,但是我们写的代码真的高效吗?你真的会用这门语言吗?带着这些疑问来到我们今天的测试项目。
循环语句是我们在编程中经常书写的代码,我们通常会使用循环对数组、集合、列表进行遍历,但是每种循环语句的实现各不相同,今天我们就对for、foreach
这两个最常用的语句进行一个简单的性能测试。
这次测试不包含内置函数的测试,例如array_map
等回调类型的函数,也不对while、do...while
语句进行测试,毕竟用while、do...while
遍历数据的情况较少。
其实早在2018年的时候做过这样的一个测试,但是不严谨,具体可以看之前这篇文章: PHP循环性能测试
测试方法
使用for、foreach、foreach-key
三种方式进行嵌套空循环测试,每一层循环1000次,且每种方式运行5次,记录每次运行的耗时,取最小值作为最终测试结果。
测试代码算法例子:
$test_result = [];
for($t = 0; $t < 5; $t++) {
$start_time = microtime(true);
for($i = 0; $i < 1000; $i++) {
for($j = 0; $j < 1000; $j++) {
// do something
}
}
$end_time = microtime(true);
$test_result[] = ($end_time-$start_time)*1000;
}
echo 'for:'.min($test_result).PHP_EOL;
测试环境
硬件环境 | |
---|---|
CPU | 单核 Intel(R) Xeon(R) Platinum 8255C CPU @ 2.50GHz |
内存 | 2GB |
硬盘 | 60GB SSD云硬盘 |
操作系统 | Ubuntu Server 20.04 LTS 64bit |
软件环境 |
---|
PHP 5.6.40 |
PHP 7.4.23 |
PHP 8.0.10 |
完整测试代码
<?php
function _for($test_count = 5, $loop_count = 1000) {
$test_result = [];
for($t = 0; $t < $test_count; $t++) {
$start_time = microtime(true);
for($i = 0; $i < $loop_count; $i++) {
for($j = 0; $j < $loop_count; $j++) {
// do something
}
}
$end_time = microtime(true);
$test_result[] = ($end_time-$start_time)*1000;
}
echo 'for:'.min($test_result).PHP_EOL;
}
function _foreach($test_count = 5, $loop_count = 1000) {
$test_result = [];
$array = range(1, $loop_count);
for($t = 0; $t < $test_count; $t++) {
$start_time = microtime(true);
foreach($array as $value) {
foreach($array as $value2) {
// do something
}
}
$end_time = microtime(true);
$test_result[] = ($end_time-$start_time)*1000;
}
echo 'foreach:'.min($test_result).PHP_EOL;
}
function _foreach_key($test_count = 5, $loop_count = 1000) {
$test_result = [];
$array = range(1, $loop_count);
for($t = 0; $t < $test_count; $t++) {
$start_time = microtime(true);
foreach($array as $key => $value) {
foreach($array as $key2 => $value2) {
// do something
}
}
$end_time = microtime(true);
$test_result[] = ($end_time-$start_time)*1000;
}
echo 'foreach-key:'.min($test_result).PHP_EOL;
}
_for();
_foreach();
_foreach_key();
测试结果
PHP5.6.40
PHP7.4.23
PHP8.0.10
测试方法 | PHP 5.6.40 | PHP 7.4.23 | PHP 8.0.10 |
---|---|---|---|
for | 21.636962890625 | 13.252973556519 | 4.356861114502 |
foreach | 46.972036361694 | 19.38009262085 | 6.3300132751465 |
foreach-key | 53.551197052002 | 34.902095794678 | 10.4660987854 |
以上耗时结果均为毫秒单位,值越小越好
从上面的结果可以看出,新版本对性能的提升确实非常大,基本上都是质的提升。如果可以尽量使用最新的稳定版。
PHP8对比PHP7基本是3倍的性能提升。
结束语
这次测试结果还是让我很意外,本以为PHP7性能提升得已经够多了,没想到PHP8直接碾压,再加上PHP8引入的JIT(Just In Time),让PHP8非常乐观,不过到目前我还没弄懂在哪些情况下才会用到JIT,如果后面有时间我会专门写一篇文章来测试JIT。
这篇文章的目的只是参考作用,毕竟只是空循环,实际应用中可能会复杂很多。但有一点可以肯定,新版本带来的性能提升是毋庸置疑的,大家可以放心食用~
评论 (0)