Javascript reverse loop slower when working with arrays?

Many of us probably already know this:

var list = ... var index = list.length while( index-- ) { // do something } 

This is supposedly the fastest way to make a loop in javascript, since you are avoiding the extra test. So far, in recent years, I have used this technique when working with data, where speed is important, and the order does not matter.

But now I stumbled upon an article which says that it is actually slower when working with arrays .

Which makes you avoid an extra test (compared to the standard for the cycle). But you know what? it will be much slower than using the correct order. Since all processor caches in the world expect that processing will be "direct", you will skip the cache again and again, and a 2x slowdown is what you get when you are lucky.

So do not go back unless you have good reason for this.

Source: https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/

Now I'm curious! I have only limited options for testing these things, and every other place I have found still says that the reverse loop is the fastest possible way (even a few stackoverflow answers). Is this really true when working with (possibly large) arrays?

And before the question of premature optimization comes up (as is often the case with questions of this type): this is basically just curiosity and yes, in things like games, performance matters!

About jsperf: So far, jsperf seemed to imply that the reverse loop is faster (I cannot check the tests now, since it does not download the result to any ATM - so I recall what I saw before). Here is the source of this question: two pieces of information contradict each other - at least if what is indicated in this article is true! So what is β€œright” in the end?

+6
source share
1 answer

The argument in this argument is incorrect. CPU caches provide advantages in orderly access to memory, because they cache memory blocks, and if you look at the memory in order, you will successively click on the same block several times, instead of loading the block each time.

However, if you go forward or backward in such a linear progression, it does not matter if this is applicable.

There can be many different factors in a game that influence the relative performance of such alternatives (not least if the engine is trying to optimize certain common patterns, which may mean that those who seem to do more work than the opponent actually do less) . Such factors can also vary significantly across platforms.

But this specific reason for waiting for direct access will not be successful.

0
source

All Articles