Improved JavaScript for Javascript loop

I just installed Aptana Studio for development, and one of the available commands for Javascript inserts a for loop as follows:

for (var i=0; i < Things.length; i++) { Things[i] }; 

Another option: Insert is improved for the loop as follows:

 for (var i = Things.length - 1; i >= 0; i--){ Things[i] }; 

Why is this last better than the first?

+9
performance javascript for-loop
Jul 05 '13 at 8:18
source share
4 answers
 // ( A ) ( B ) (C) for (var i=0; i < Things.length; i++) { Things[i] }; 
  • A is executed once before starting the loop.
  • B is reevaluated before each iteration, and if it is not, it exits the loop (therefore, it checks the length Things property on each iteration.)
  • C is executed after each iteration

However, the performance that you get from changing the loop is minimal, and you risk sacrificing some of the readability, so stick to what you consider to be the most readable and not what is the most correct in terms of performance.




This may make more sense to you:

 for (var i=0; i < Things.length; i++) { Things[i] = null; }; 

can be rewritten as follows:

 var i = 0; //A while (true) { if (!(i < Things.length)) { //B - We check the length all the time break; } Things[i] = null; i++; //C } 

and

 for (var i = Things.length - 1; i >= 0; i--){ Things[i] = null; }; 

can be rewritten as follows:

 var i = Things.length - 1; //A - We only check the length once while (true) { if (!(i >= 0)) { //B break; } Things[i] = null; i--; //C } 
+11
Jul 05 '13 at 8:44
source share

Because the result of Things.length does not get an estimate every time (at each iteration). It was simply appointed once at the beginning and used from now on. In addition, the number of iterations is obviously the same.

Its micro optimization really. You will find more interesting things to optimize your code, which I assume.

+4
Jul 05 '13 at 8:22
source share

How about this?

 for (var i = 0, len = things.length; i < len; i += 1) { // something } 

Update:

Sorry, English is not my first language. So I have no idea how to start a conversation with you guys. Anyway, here is the Youtube URL, and I learned from this video. Hope this helps you. This explains why!

https://www.youtube.com/watch?v=mHtdZgou0qU

+4
Feb 24 '16 at 8:16
source share

I assume that on the second you only get access to Things.length once (when initializing i ), where on the first you get access to it every time to check if you are there.

+1
Jul 05 '13 at 8:24
source share



All Articles