问题描述
鉴于此代码:
var arr = [];
for (var i = 0; i < 10000; ++i)
arr.push(1);
前锋
for (var i = 0; i < arr.length; ++i) {}
向后
for (var i = arr.length - 1; i >= 0; --i) {}
硬编码转发
for (var i = 0; i < 10000; ++i) {}
为什么向后退得这么快?
Why is backwards so much faster?
这是测试:
推荐答案
因为你的远期条件必须收到你的长度
属性每次都是数组,而另一个条件只需要检查大于零,一个非常快的任务。
Because your forwards-condition has to receive the length
property of your array each time, whilst the other condition only has to check for "greater then zero", a very fast task.
当你的数组长度在循环期间没有改变时,你真的看看ns-perfomance,你可以使用
When your array length doesn't change during the loop, and you really look at ns-perfomance, you can use
for (var i=0, l=arr.length; i<l; i++)
BTW:而不是 for(var i = arr.length; i> 0; --i)
您可以使用代替(var i = arr.length; i - > 0;)
实际上你的数组从n-1到0,而不是从n到1。
BTW: Instead of for (var i = arr.length; i > 0; --i)
you might use for (var i = arr.length; i-- > 0; )
which really runs through your array from n-1 to 0, not from n to 1.
这篇关于为什么向后遍历数组的速度比向前快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!