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

So, I was doing some micro-optimization in Node.js. I notice that with multithreading, there is a huge first message delay for child processes. Take the following code for example:

LAUNCH 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 am doing is creating a child process and sending it messages, which it will respond to immediately. I measure the time between sending a message and receiving a response. The following output happens almost every time:

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

      

There is a huge delay between the first message / response link. And I've noticed this for other projects I've done with child processes. Why is this happening? How can I fix this?

Edit: After some debugging, the delay appears to occur after the first one child.send

for the first callback process.on

. There is almost no delay in the response process of the child process.

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

+3


source to share





All Articles