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.
-
1There is no "performance" issue. For all practical purposes they take the same amount of work: use the form that is most clear.user2864740– user28647402014年08月12日 06:59:21 +00:00Commented Aug 12, 2014 at 6:59
-
Hi, suggestion well appreciated, can you provide me a sample fiddle about stress testing about my code? Thanks,user3932204– user39322042014年08月12日 07:02:16 +00:00Commented 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.Denys Séguret– Denys Séguret2014年08月12日 07:03:19 +00:00Commented 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++) {}user3932204– user39322042014年08月12日 07:05:37 +00:00Commented Aug 12, 2014 at 7:05
-
1You'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.Denys Séguret– Denys Séguret2014年08月12日 07:10:02 +00:00Commented Aug 12, 2014 at 7:10
1 Answer 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.