Pergunta

This is relevant, b.c. I want to test looping structures. What I normally do is put in a simple statement like

i++

in the loop. I do this b.c. I wonder if a smart interpreter will not run empty blocks. For example.

for(var i = 0; i < 10; i++) {
}

might not loop at all as there is nothing in the loop.

so I normally do something like:

for(var i = 0; i < 10; i++) {
    i++;
}

But this does test the i++ statement as well as the loop structure, which I don't want.

Foi útil?

Solução

Here look at this. Notice the delay when trying to show the alert: http://jsfiddle.net/xs724/

for(var ii = 0; ii < 1000000000; ii++){}
alert("DONE");

I tested this in chrome. It most likely could vary from browser to browser.

JsPerf Link: http://jsperf.com/js-optimizationlooping

Outras dicas

The answer is: You never know. There are lots of optimizations going on in modern JavaScript engines. One example is dead code elimination, which skips code that does not influence the end result.

There was a quite interesting controversy about this feature in IE9: http://digitizor.com/2010/11/17/internet-explorer-9-caught-cheating-in-sunspider-benchmark/

But why would you want to run an empty block over and over anyway?

If you want the JavaScript interpreter to simply wait try this answers:
What is the JavaScript version of sleep()?
Sleep in Javascript - delay between actions

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top