简体   繁体   中英

Node js, why is setTimeout with 50ms is faster than setTimeout 0

I'm a Node.js developer for a year now. Last night I thought I'd do a benchmark between express and http module, basically it is a simple promise that returns a string and it is passed to the response, now i saw that http is quite faster, but I came to a different problem, if I set setTimeout to 50 ms in the ab test with a concurrency of 500 and a 100000 requests, the response times are twice faster than setTimeout 0 or process.nextTick .

Now I know that setTimeout takes it to the next cycle but at the end of the queue, nextTick puts it first on the next cycle, but I really do not understand why setTimeout 50ms is faster than setTimeout 0. even without setTimeout, the ab test is a lot slower than setTimeout 50ms.

I suspect its something with the apache ab test or maybe i missed something with node?

http.createServer((req,res)=>{
  setTimeout(()=>{
    check().then(data=>{
      res.write(data);
      res.end();
    })
  },0)

}).listen(3000);

let check = () =>{
  return Promise.try(()=>{
    return 'done with Async'
  })
};

// setTimeout 0 times with ab test
Concurrency Level:      500
Time taken for tests:   53.824 seconds
Complete requests:      100000
Failed requests:        0
Total transferred:      9000000 bytes
HTML transferred:       1500000 bytes
Requests per second:    1857.90 [#/sec] (mean)
Time per request:       269.121 [ms] (mean)
Time per request:       0.538 [ms] (mean, across all concurrent requests)
Transfer rate:          163.29 [Kbytes/sec] received

// setTimeout 50ms response times
Concurrency Level:      500
Time taken for tests:   23.174 seconds
Complete requests:      100000
Failed requests:        0
Total transferred:      9000000 bytes
HTML transferred:       1500000 bytes
Requests per second:    4315.12 [#/sec] (mean)
Time per request:       115.872 [ms] (mean)
Time per request:       0.232 [ms] (mean, across all concurrent requests)
Transfer rate:          379.26 [Kbytes/sec] received

When you use setTimeout(0), you are adding an extra job on the process which may takes some tick. But using setTimeout(50), requests get to be ready in queue and after 50ms, they will be sent altogether whiteout extra ticks of time. For example consider a request takes 10ms to be sent and 10ms for getting response. By using setTimeout(50), sending 500 requests will take 5000ms plus 50ms for timeout and 10ms for response, it will spend 5060ms. Now if we use setTimeout(0), we will have 10ms for sending request and 10ms for getting response. Therefore, for 500 requests, it will spend 10000ms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM