date - setTimeout in javascript make function run faster - Stack Overflow

I have an application which I have to push a lot values to array, so I test the execution time:var st =

I have an application which I have to push a lot values to array, so I test the execution time:

var st = new Date().getTime();
var a = [];
for (var i = 0; i < 20971520; i++) {
  a.push(i);
}
var ed = new Date().getTime();
console.info((ed - st) / 1000);
console.info(a.length);

I run the codes in Firefox Console and Chrome console directly, and it cost 37 seconds. And during the execution, even the mouse can be moved in Chrome, but there is no interactive effect.

Then I change the codes:

function push() {
  var st = new Date().getTime();
  var a = [];
  for (var i = 0; i < 20971520; i++) {
    a.push(i);
  }
  var ed = new Date().getTime();
  console.info((ed - st) / 1000);
  console.info(a.length);
}

var tr = setTimeout(push, 50);

Simplify put the codes in a function, and call it using the setTimeout, it cost 0.844 second. And during the execution, I can operation in Chrome normally.

What's going on here?

I know that the setTimeout will put the control to the browser to do the UI job, which will make the page responsive. For example, when I do some calculation during the mousemove of the page, I would put the calculation executed delayed to prevent it blocking the UI.

But why it reduce the total execution time of the same codes?

I have an application which I have to push a lot values to array, so I test the execution time:

var st = new Date().getTime();
var a = [];
for (var i = 0; i < 20971520; i++) {
  a.push(i);
}
var ed = new Date().getTime();
console.info((ed - st) / 1000);
console.info(a.length);

I run the codes in Firefox Console and Chrome console directly, and it cost 37 seconds. And during the execution, even the mouse can be moved in Chrome, but there is no interactive effect.

Then I change the codes:

function push() {
  var st = new Date().getTime();
  var a = [];
  for (var i = 0; i < 20971520; i++) {
    a.push(i);
  }
  var ed = new Date().getTime();
  console.info((ed - st) / 1000);
  console.info(a.length);
}

var tr = setTimeout(push, 50);

Simplify put the codes in a function, and call it using the setTimeout, it cost 0.844 second. And during the execution, I can operation in Chrome normally.

What's going on here?

I know that the setTimeout will put the control to the browser to do the UI job, which will make the page responsive. For example, when I do some calculation during the mousemove of the page, I would put the calculation executed delayed to prevent it blocking the UI.

But why it reduce the total execution time of the same codes?

Share Improve this question edited Feb 4, 2018 at 19:30 Salman Arshad 272k84 gold badges443 silver badges534 bronze badges asked Jan 6, 2015 at 8:30 hguserhguser 36.1k55 gold badges172 silver badges302 bronze badges 7
  • 1 Maybe it's just caching. Have you tried to swap the execution order, i.e. first run the setTimeout variant and then the other one? – GOTO 0 Commented Jan 6, 2015 at 8:38
  • What happens if you just call push() ? – Freez Commented Jan 6, 2015 at 8:40
  • It takes the same time with or without the timeout for me. – DoctorMick Commented Jan 6, 2015 at 8:43
  • 3 Running code in the console should not be seen as a reasonnable way to test execution speed. Code in a function is optimized by the engine. – Denys Séguret Commented Jan 6, 2015 at 8:47
  • @dystroy: It seems that you are right, since I found that execute push() directly will cost the same time as that of using the setTimeout. – hguser Commented Jan 6, 2015 at 8:57
 |  Show 2 more ments

4 Answers 4

Reset to default 5

And during the execution, I can operation in Chrome normally.

Not true. The main chrome window will be just as frozen as the other case (just for a shorter while). The debug tools are a separate thread and will not slow down though.

But why it reduce the total execution time of the same codes?

It does if you run in dev tools. If you execute the code in actuality where the VM can make property optimizations the times are parable (nearly 1 second). e.g.

   var st = new Date().getTime();
   var a = [];
   for (var i = 0; i < 20971520; i++) {
       a.push(i);
   }
   var ed = new Date().getTime();
   console.info('normal', (ed - st) / 1000);
   console.info(a.length);

   function push() {
       var st = new Date().getTime();
       var a = [];
       for (var i = 0; i < 20971520; i++) {
           a.push(i);
       }
       var ed = new Date().getTime();
       console.info('timeout', (ed - st) / 1000);
       console.info(a.length);
   }

   var tr = setTimeout(push, 0);

http://jsfiddle/gu9Lg52j/ you will see the normal executes just as fast as setTimeout.

Also if you wrap the code in a function and execute in a console the time will be parable even without a setTimeout as the VM can make optimizations between function definition and execution:

  function push() {
       var st = new Date().getTime();
       var a = [];
       for (var i = 0; i < 20971520; i++) {
           a.push(i);
       }
       var ed = new Date().getTime();
       console.info('timeout', (ed - st) / 1000);
       console.info(a.length);
   }
   push();

Both variations of code should run with almost identical speed (the latter example might be faster but not 10 times faster).

Inside the Chrome developer tools, there is a different story. The expressions are evaluated inside a with block. This means the variables such as a and i are first searched inside another object (the __mandLineAPI). This adds an additional overhead which results in the 10 times longer execution time.

All JavaScript engines perform various optimizations. For example V8 uses 2 pilers, a simple one used by default and an optimizing one. Code not piled by the optimizing piler is slow, very slow.

A condition for the optimizing piler to run is that the code must be in a (not too long) function (there are other conditions). The first code you tried in the console isn't in a function. Put your first code in a function and you'll see it performs the same than the second one, setTimeout changes nothing.

It makes zero sense to check for performances in the console when the main performance factor is the optimizing pilation. If you're targeting node, use a benchmarking framework. If you're targeting the browser, use a site like jsperf.

Now, when you have to do a really long putation in the browser (which doesn't seem to be the case here), you should consider using web workers which do the job in a background thread not impacting the UI.

setTimeout, like others noticed, doesn't speed up the array creation and does lock the browser. If you are concerned about browser lockup during the array creation, web workers (see MDN) may e to the rescue. Here is a jsFiddle demo using a web worker for your code. The worker code is within the html:

onmessage = function (e) {
   var a = [], now = new Date;
   for (var i=0; i<20971520; i++) {
     a.push(i);
   }
   postMessage({timings: 'duration: '+(new Date()-now) + 
                         'Ms, result: [' + a[0] + '...'+a[a.length-1] + ']'});
 }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742397007a4436152.html

相关推荐

  • date - setTimeout in javascript make function run faster - Stack Overflow

    I have an application which I have to push a lot values to array, so I test the execution time:var st =

    14小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信