Hello. The cycle should run about a million times. At the same time you need to keep within the minimum time. I know for example in php certain cycles (especially for arrays) work faster than others (for example, foreach). Is there anything similar in javascript?

Supplemented.

Here is the cycle that should be executed a million times =):

for (i = 0; i < n; i++) { t = t + '<tr>'; for (j = 0; j < n; j++) { t = t + '<td></td>'; } t = t + '</td>'; } 

    4 answers 4

    Webo.in has interesting articles about script acceleration. In your case, the " Performance of simple and complex constructions in JavaScript ."

    • Thank you for the article! - Jet

    It all depends on what is the condition for exiting the loop. The complexity of the cycle depends on the complexity and frequency of checking the condition of exit from it. And this condition depends on the original problem. In some cases, the good old

     for(var i = 0, m = ...; i < m; ++i) {} 

    and in some do or while .

    • Added a cycle to the question. - Jet

    JavaScript has an analogue foreach

     for( var item in list ) 
    • item - item
    • list - can be an array or a regular object
    • This analog is not exactly analogous. Cannot be used for arrays, as it works differently on different browsers. I don’t remember the details, length falls on some along with the elements of the array, but not on some. - cy6erGn0m
    • Absolutely right. Moreover, in the above article, the test cycles. The result showed that the for-in loop is very slow for all browsers and especially for IE. In general, if performance and speed is important to you, do not use it. - Jet
    • Yes you are right. I also came across. But this cycle is very convenient to use if you use an object as an associative array. - KiTE

    I am young. Can not understand the question) Once suffered garbage.

     <html> <head><title></title></head> <body> <script> alert('dddd') i=1; while (i<10000000) { alert('ghgj'); i ++ } </script> </body> </html> 
    • I'm talking about the speed of the script. And in your case, the cycle will be repeated only after pressing "ok" in the alert window .. - Jet
    • Well, yes, you can remove the alert) Then the correct answer is # 2) Just below the guy wrote correctly) - Aleksey Makas