Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
988 views
in Technique[技术] by (71.8m points)

performance - Javascript improved native for loop

I have just installed Aptana Studio for development and one of the available commands for Javascript is Insert a for loop like this:

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

Another option is Insert improved for loop like this:

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

Why this last one is better than the first one?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
//   (  A  )  (       B       )  (C)
for (var i=0; i < Things.length; i++) {
  Things[i]
};
  • A is executed once before the loop starts.
  • B is re-evaluated before every iteration, and if it's not true, it exits the loop (hence it checks the length property of Things on every single iteration.)
  • C is executed after every iteration

That said, the performance you get from changing the loop is minimal, and you risk sacrificing part of the readability, so stick with what you find most readable - not what is most correct performance-wise.


This might make more sense for you:

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

could be rewritten as the following:

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;
};

could be rewritten as the following:

var i = Things.length - 1; //A - We only check the length once
while (true) {
    if (!(i >= 0)) { //B
        break;
    }
    Things[i] = null;
    i--; //C
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...