简体   繁体   English

当需要正向计数时,是否有更好,更快,更易读的方式使循环有效?

[英]Is there a better, faster, more readable, way to make looping efficient when forward counting is needed?

I've been reading a lot about loops. 我已经阅读了很多有关循环的文章。 I've lerned that the fastest way to do a loop in javascript is when you 我认为在JavaScript中执行循环的最快方法是当您

var i=10; var i = 10; while(i--){console.log(i);} while(i-){console.log(i);}

this will start at nine end at zero because zero is false. 这将从九个零开始,因为零为假。 It looks like it's fast because it does seems to only do the one check while also setting at the same time (each browser performs differently, please don't shoot me!) 看来它之所以快,是因为它似乎只进行了一次检查,同时也同时进行了设置(每个浏览器的执行效果都不同,请不要射击我!)

From all that I have seen though, this isn't always practical (as you are counting down) 从我所看到的所有内容来看,这并不总是可行的(因为您正在倒数)

As this article states in point 3 http://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ ; 如本文第3点所述, http://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ ; you may be looping through an array and Quote 您可能正在遍历数组和Quote

"Because all CPU caches in the world expect the processing to be 'straight'" “因为世界上所有的CPU缓存都希望处理是“直接的””

Also if yo need the number++ in the loop for a calculation like so 另外如果你需要循环中的数字++这样的计算

for(var importantNumber=0;importantNumber<10;importantNumber++){console.log(importantNumber);}

I think that will check both sides of < on each loop 我认为这将检查每个循环上的<

or 要么

importantNumber=0;

while(importantNumber<10){console.log(importantNumber);importantNumber++;}

I think the above is pretty the same as the first 我认为以上与第一个相同

importantNumber+=1; ImportantNumber + = 1; would improve it 会改善它

while(importantNumber<10){console.log(importantNumber);importantNumber+=1;}

how about one number that is polar oposite to the other 一个与另一个相反的数字怎么样

var i=[0,10];// i[0] is the importantNumber

while(i[1]-=1){console.log(i[0]);i[0]+=1;}

Is there a better, faster, more readable, less goofy way to make looping efficient when forward counting is needed? 当需要向前计数时,是否有更好,更快,更易读, 轻松的方法来使循环有效?

It is important I feel when dealing with large loops or many loops in sequence or large arrays and big calculations else this is not an issue in normal situations 在处理大型循环或序列中的多个循环或大型数组和大型计算时,我感到很重要,否则在正常情况下这不是问题

I'm sure you've come across this quote before: "Premature optimization is the root of all evil" . 我敢肯定,您之前遇到过这句话: “过早的优化是万恶之源” And perhaps you're familiar with this one, too: "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." 也许您也对此很熟悉: “调试是一开始编写代码的两倍。因此,如果您尽可能聪明地编写代码,那么就定义而言,您还不够聪明,无法进行调试它。”

Both of these quotes ring true. 这两个引用都是正确的。 You are talking about writing loops. 您正在谈论编写循环。 Loops are basic structures, essential building bricks of (almost) any piece of code. 循环是基本结构,是(几乎)任何代码的必不可少的构件。 Compare it to building a wall: Yes, you could save a few cents by keeping bricks that have broken in half, and use those halves when you find yourself in need of half a brick. 比较一下它与建造一堵墙:是的,您可以保留一半的砖块,这样可以节省几分钱,而当您需要一半的砖块时,可以使用这些一半。 But is it really worth it? 但这真的值得吗? I mean: look at the last snippet you posted here. 我的意思是:看看您在此处发布的最后一个片段。 By your own admission, it looks goofy , and isn't all that readable. 您自己承认,它看起来很愚蠢 ,而且可读性不强。
KISS is key: perhaps, in some cases, on some JS engines, a decrementing while loop will outperform an incrementing for loop, but you're writing JavaScript not C, or assembly. KISS是关键:也许在某些情况下,在某些JS引擎上,递减的while循环将胜过递增的for循环,但您编写的不是JavaScript或C语言。 The mere fact that you're writing JS means that losing or gaining a few micro-seconds isn't going to be noticeable. 您正在编写JS的事实本身就意味着丢失或增加几微秒将不会引起注意。

It all boils down to common sense: Write what you know , and write it so that you can understand the code at a glance. 一切都归结为常识:写下您所知道的内容 ,然后编写它,以便您一眼就能理解代码。
If that means writing: 如果那意味着写:

var i=10;
while(i--)//note, this will never log array[0]!!!
    console.log(array[10-i]);

Then I'd have to say: get help, but no matter. 然后我不得不说:得到帮助,但是没关系。 If that's what is most readable to you, then that's what you write. 如果那是您最易读的内容,那就是您所写的内容。 However, I will say this: 但是,我会这样说:

while( --i)
    console.log(array[10-i]);

Will not perform the way you expect it to (pre-increment vs post-increment - or decrement in this case). 不会按照您期望的方式执行(先增量还是后增量-在这种情况下是递减)。 Perhaps the closest you can get with a while loop in terms of predictable behavriour, or behaviour resembling that of a for loop is either one of this: 也许就可预测的行为而言,使用while循环可以获得的最接近的结果,或者类似于for循环的行为是以下之一:

var i = 0;
while(i < array.length)
    console.log(array[i++]);
//or
i = array.length;
while(i)
    console.log(array[array.length - (i--)]);

But let's be honest, compared to: 但说实话,相比之下:

for (var i = 0;i<array.length;++i)
    console.log(array[i]);

I'd say it's pretty obvious which code makes the most sense. 我想说的是,哪个代码最有意义。 What might impact the performance here is how array.length is implemented. 这里可能影响性能的是如何实现array.length Chrome/chromium translates all objects (this of course includes arrays) to hidden C++-like classes, which in turn means that array.length is an O(1) operations (accessing a member), whereas IE engines of old implemented this magic property differently, which caused it to perform an order of magnitude slower. Chrome / chromium将所有对象(当然包括数组)转换为类似于C ++的隐藏类,这反过来意味着array.lengthO(1)操作(访问成员),而旧版IE引擎实现了此魔术属性不同的是,这导致其执行速度降低了一个数量级。 However: don't worry about this difference. 但是:不要担心这种差异。 Engines evolve, and by the time you've finished optimizing your loops to get a consistent speed across all browsers, the next version will have been released, and you can start all over again. 引擎不断发展,当您完成优化循环以在所有浏览器上获得一致的速度时,下一版本将发布,您可以重新开始。 So TL;TR: 所以TL; TR:

Never mind the Bollocks 别介意伯洛克

I've been reading a lot about loops. 我已经阅读了很多有关循环的文章。 I've lerned that the fastest way to do a loop in javascript is when you [while loop] 我认为在javascript中执行循环的最快方法是[while循环]

Loops in javascript in modern browsers are highly optimised, there is usually little or no difference in current browsers between for, while and do loops. 现代浏览器中的javascript循环得到了高度优化,for,while和do循环之间当前浏览器之间通常几乎没有差异。 There were differences a few years back, but they were inconsistent across browsers so what was faster in one wasn't in another. 几年前存在差异,但是在浏览器之间并不一致,因此在一个浏览器中更快的速度在另一个浏览器中没有。

So just use the loop that suits and if there is a performance issue, investigate. 因此,请使用适合的循环, 如果存在性能问题,请进行调查。 It will generally have little or nothing to do with the type of loop. 通常,它与循环的类型几乎没有关系。

It looks like it's fast because it does seems to only do the one check while also setting at the same time 看起来好像很快,因为它似乎只进行了一次检查,同时也进行了设置

Not necessarily. 不必要。 It's less typing to write it that way, but often it's faster to do assignments separately to the test (but the difference is small either way), eg 这样写的类型较少,但是通常单独进行测试分配会更快(但两种方法的差异都很小),例如

while (i) {
  --i;
}

may well be faster, or at least no slower than, 可能会更快,或者至少不会慢于

while (--i) {
  ...
}

But again, use whichever seems appropriate in the context of the surrounding code. 但是同样,请在周围代码的上下文中使用任何合适的方法。 See Elias' answer regarding premature optimisation. 请参阅Elias关于过早优化的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM