为什么settimeout()序列会影响性能?

时间:2017-07-31 13:03:29

标签: javascript settimeout

有两个类似的javascript程序A和B.(在Chrome 59.0.3071.115(64位)中测试)。程序参考Scheduling: setTimeout and setInterval

程序A :(运行约5858ms)

<script type="text/javascript">
let i = 0;
let start = Date.now();

function count() {

  // move the scheduling at the beginning
  if (i < 1e9 - 1e6) {
    setTimeout(count, 0); // schedule the new call
  }

  do {
    i++;
  } while (i % 1e6 != 0);

  if (i == 1e9) {
    alert("Done in " + (Date.now() - start) + 'ms');
  }

}

count();

</script>

程序B(运行约11294ms)

<script type="text/javascript">

let i = 0;

let start = Date.now();

    function count() {

       // do a piece of the heavy job (*)
      do {
         i++;
      } while (i % 1e6 != 0);


      if (i == 1e9) {
        alert("Done in " + (Date.now() - start) + 'ms');
      } else {
        setTimeout(count, 0); // schedule the new call (**)
      }


    }

    count();

    </script>

程序C(大约接近A)

<script>
    let i = 0;
    let start = Date.now();

    function count() {

      if (i == 1e9) {
        alert("Done in " + (Date.now() - start) + 'ms');
      } else {
        setTimeout(count, 0); // schedule the new call (**)
      }
    // do a piece of the heavy job (*)
      do {
        i++;
      } while (i % 1e6 != 0);

    }
    count();
</script>

我知道javascript是单线程,而settimeout只是在指定的延迟后进入队列进行执行。比较两个代码,我无法理解为什么程序A在单线程下比程序B快。

这就是我的想法excuteQueue.jpg

1 个答案:

答案 0 :(得分:0)

基本区别是:

1)sets a timer, does a heavy job
2)does a heavy job, sets a timer

正如Pointy所指出的那样,0ms定时器等待的时间总是超过0ms,所以基本上就是这样:

1)
*sets a timer   |
*do heavy job  |
*                       \/
* timer finishes, next job

2)
*do a heavy job
*sets a timer |
*                      |
*                     \/
* timer finishes, next job

如您所见,第二个收益率更长。