Skip to content

Commit ddcd1a2

Browse files
yprestoitaloacasas
authored andcommitted
child_process: optimize IPC for large data
Squashed from: - child_process: stop indexOf() on whole IPC buffer - child_process: get rid of forEach() and slice() in IPC - child_process: get rid of another forEach() in IPC Fixes: #3145 PR-URL: #10557 Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: Anna Henningsen <[email protected]>
1 parent 2f339e7 commit ddcd1a2

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

lib/internal/child_process.js

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -446,14 +446,20 @@ function setupChannel(target, channel) {
446446
channel.onread = function(nread, pool, recvHandle) {
447447
// TODO(bnoordhuis) Check that nread > 0.
448448
if (pool) {
449-
jsonBuffer += decoder.write(pool);
450-
451-
var i, start = 0;
449+
// Linebreak is used as a message end sign
450+
var chunks = decoder.write(pool).split('\n');
451+
var numCompleteChunks = chunks.length - 1;
452+
// Last line does not have trailing linebreak
453+
var incompleteChunk = chunks[numCompleteChunks];
454+
if (numCompleteChunks === 0) {
455+
jsonBuffer += incompleteChunk;
456+
this.buffering = jsonBuffer.length !== 0;
457+
return;
458+
}
459+
chunks[0] = jsonBuffer + chunks[0];
452460

453-
//Linebreak is used as a message end sign
454-
while ((i = jsonBuffer.indexOf('\n', start)) >= 0) {
455-
var json = jsonBuffer.slice(start, i);
456-
var message = JSON.parse(json);
461+
for (var i = 0; i < numCompleteChunks; i++) {
462+
var message = JSON.parse(chunks[i]);
457463

458464
// There will be at most one NODE_HANDLE message in every chunk we
459465
// read because SCM_RIGHTS messages don't get coalesced. Make sure
@@ -462,10 +468,8 @@ function setupChannel(target, channel) {
462468
handleMessage(target, message, recvHandle);
463469
else
464470
handleMessage(target, message, undefined);
465-
466-
start = i + 1;
467471
}
468-
jsonBuffer = jsonBuffer.slice(start);
472+
jsonBuffer = incompleteChunk;
469473
this.buffering = jsonBuffer.length !== 0;
470474

471475
} else {
@@ -494,9 +498,10 @@ function setupChannel(target, channel) {
494498
var queue = target._handleQueue;
495499
target._handleQueue = null;
496500

497-
queue.forEach(function(args) {
501+
for (var i = 0; i < queue.length; i++) {
502+
var args = queue[i];
498503
target._send(args.message, args.handle, args.options, args.callback);
499-
});
504+
}
500505

501506
// Process a pending disconnect (if any).
502507
if (!target.connected && target.channel && !target._handleQueue)

0 commit comments

Comments
 (0)