best way to loop an array [closed]
var data = [];
for (i = 0, len = data.length; i < len; i++) {
for (i = 0, i < data.length; i++) {
What is the difference between these two way of forming an loop
and which is sited as best among them.
Calling the first one is cheaper than the second one. Is it true?
Yes, it is - according to:
http://blogs.oracle.com/greimer/entry/best_way_to_code_a
Note: you could easily build a test if you are not convinced.
In the first case, you'll have an additional len
variable the holds data.length
. You can do this if you need the value of data.length
again inside the for loop (f.e. if retrieving it is computionally expensive).
But note that it is the same as
len = data.length;
for (i = 0; i < len; i++) {
which I'd prefer for readability.
It strongly depends of the language. Most compilers will see length to be a loop invariant and move it outside itself. This kind of details are of little importance, the real important thing in loop is to have loops that are cache friendly , ie go down your data in a way cache spatial and temporal locality is maximal.
精彩评论