2

this is actually my first post about javascript. Would like to know, the performance of the following code as it is a "Decrementing while loop" inside that while loop has an Incrementing variable.

var i = data.d.length;
var i_counter=0;


while (i--)
{
   console.log(i_counter++)
}

My reason for adding i_counter++ is for sorting purposes. Would it slightly affect the loops performance for thousand of records? Would this code below much better than aboves performance?

for (var i = 0; i < data.d.length; i++) {
   console.log(i)
}

I have seen an online loop stress test online and this shows that decrementing while is the best. Is it true? http://jsperf.com/fastest-array-loops-in-javascript/32 Please give me a fiddle to stress test the code. Thank you. Suggestions are well accepted.

8
  • 1
    There is no "performance" issue. For all practical purposes they take the same amount of work: use the form that is most clear. Commented Aug 12, 2014 at 6:59
  • Hi, suggestion well appreciated, can you provide me a sample fiddle about stress testing about my code? Thanks, Commented Aug 12, 2014 at 7:02
  • The only slow operation we can see is the console.log. That is costly. Decrementing or incrementing isn't. Commented Aug 12, 2014 at 7:03
  • So my code provided above is still much more faster than this code?for (var i = 0; i < data.d.length; i++) {} Commented Aug 12, 2014 at 7:05
  • 1
    You're on the wrong path. That's not where your program needs optimization. You should really profile to find the hot spots before even trying to do this kind of optimizations. Commented Aug 12, 2014 at 7:10

1 Answer 1

1

In both cases the runtime is by magnitudes dominated by console.log, which performs potentially blocking IO (log functions are in general not cheap, in particular when they produce visible console/UI output).

Assuming console.log a no-op, the first code should have a slight advantage since d.length is not re-evaluated every iteration (which is two dictionary lookups in the unoptimized case). A very intelligent JS runtime may be able to avoid this out even for the second case, though.

The best advice is, to optimize last and only after profiling which parts of your code are actual bottlenecks. FF and Chrome have profiling tools built-in for this purpose.

For the perfect JS loop iteration, have a look at this related SO question. Doing an extra increment on every iteration should not dramatically affect things.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you but, sorry, please disregard the console.log.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.