问题描述
我和 Jim O'Brien 制作了两段代码,它们的作用完全相同.但哪个更快?
I and Jim O'Brien have made two snippets of code, which do exactly the same. But which is faster?
(代码使输入数组的偶数和奇数的键值对.如果输入数组是这样的:
(The code makes key-value pairs of even and odd numbers of the input array. If the input array is this:
Array(
"thirteen",
13,
"seven",
7,
...
)
那么输出数组就会变成这样:
then the output array will become this:
Array(
"thirteen" => 13,
"seven" => 7,
...
)
片段 1:
<?php
$output = array();
for ($i = 0; $i < count($input); $i++) {
$output[$input[$i]] = $input[++$i];
}
?>
代码段 2:
<?php
$output = array();
for ($i = 0; $i < count($input); $i += 2) {
$output[$input[$i]] = $input[$i + 1];
}
?>
哪个片段更快,为什么?
Which snippet is faster, and why?
推荐答案
与预先计算 count($input)
而不是运行它会节省的相比,它们之间的区别微不足道每次循环出现时.
The difference between them is insignificant compared to what you would save if you pre-computed count($input)
instead of running it every time the loop comes around.
就在您给出的两者之间,第二个更具可读性,是我会选择的一个.效率方面,根本不值得操心.
Just between the two you have given, the second is more readable and is the one I would choose. Efficiency-wise, it's just not worth bothering about.
这篇关于以下两个代码片段中哪个更快,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!