Why is there a huge first-time message delay for child processes?

Viewed 329

So I have been doing some micro-optimization in Node.js. I'm noticing that when multithreading, there is a huge first-message delay on child processes. Take the following code for example:

RUN IT HERE

index.js

var cp = require('child_process');
var child = cp.fork(__dirname + '/worker.js');

var COUNT = 10;
var start;

child.on('message', (e) => { 
  var end = Date.now();
  console.log('Response time', end - start);
  if(COUNT--) {
    sendMessage();
  } else {
    process.exit();
  }
});

function sendMessage () {
  start = Date.now();
  child.send('hi!');
}

sendMessage();

worker.js

process.on('message', e => {
  process.send('Good morning!');
});

Explanation: all i'm doing is creating a child process and sending it messages, to which it will immediately respond. I'm measuring the time between sending the message and receiving a response. The following output occurs nearly everytime:

Response time 51
Response time 0
Response time 0
Response time 0
Resp...

There is a huge delay between the first message/response couple. And I have noticed this for other projects I made with child processes as well. Why is this occuring? How can I fix it?

Edit: after some debugging, the delay seems to occur after the first child.send to the first process.on callback. There is nearly no delay in the response of the child process.

Related: https://github.com/nodejs/node/issues/3145

0 Answers
Related