为什么这段代码的执行时间更快:
$start_foreach = microtime(true);
$counter = 1;
foreach (range(1, 1000) as $number) {
$counter++;
}
$end_foreach = microtime(true);
$time_foreach = ($end_foreach - $start_foreach);
echo "\nExecution time of foreach-loop is $time_foreach second\n";
而不是:
$start_foreach = microtime(true);
$counter = 1;
foreach (range(1, 10) as $number) {
$counter++;
}
$end_foreach = microtime(true);
$time_foreach = ($end_foreach - $start_foreach);
echo "\nExecution time of foreach-loop is $time_foreach second\n";
为什么呢?我已经循环了很多次了,但是结果还是一样
请有人给我解释一下为什么会这样?
1条答案
按热度按时间clj7thdc1#
我不知道你是怎么测试的,但我的结果不一样:
运行它:
https://onlinephp.io?s=fY5BCoNADEX3gncI4mLECnVti6veQijTMdaBmkicgULp3RuhQt00u5D3fv6pncc5TdIkX4KVcB1Y0LoRzjB5Jxz8hCZIxKJRxHGkgKLHWtcNNWLpjqY-QH0swC6QU5xuKAW80gR0Nq8s1XprDlL__9G6_RBmZ1Sw77oa6EaGrKPLE10MngnWCOABvlD1YJ7Ba7ld9oKOqe8oaz4%2C&v=8.2.1
https://onlinephp.io?s=fY5BCoNADEX3gncI4mLECrq2paveQijTMdaBmkicgULp3RuhQt00u5D3fv7xPI9zmqRJvgQr4TqwoHUjnGDyTjj4CU2QiEWriONIAUWPja4basTSHU1zgKau6wLsAjnF6YZSwCtNQGczy1K9tyYh9f9frdsPYXZGBfu2q4FuZMg6ujzRxeCZYI0AHuALVQ_mGbyW22Uv6Jj6jrL2Aw%2C%2C&v=8.2.1