Skip to content

Commit c13429a

Browse files
yprestoaddaleax
authored andcommittedMay 9, 2017
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 <info@bnoordhuis.nl> Reviewed-By: Anna Henningsen <anna@addaleax.net>
1 parent 32fa37f commit c13429a

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed
 

‎lib/internal/child_process.js

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

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

459465
// There will be at most one NODE_HANDLE message in every chunk we
460466
// read because SCM_RIGHTS messages don't get coalesced. Make sure
@@ -463,10 +469,8 @@ function setupChannel(target, channel) {
463469
handleMessage(target, message, recvHandle);
464470
else
465471
handleMessage(target, message, undefined);
466-
467-
start = i + 1;
468472
}
469-
jsonBuffer = jsonBuffer.slice(start);
473+
jsonBuffer = incompleteChunk;
470474
this.buffering = jsonBuffer.length !== 0;
471475

472476
} else {
@@ -495,9 +499,10 @@ function setupChannel(target, channel) {
495499
var queue = target._handleQueue;
496500
target._handleQueue = null;
497501

498-
queue.forEach(function(args) {
502+
for (var i = 0; i < queue.length; i++) {
503+
var args = queue[i];
499504
target._send(args.message, args.handle, args.options, args.callback);
500-
});
505+
}
501506

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

0 commit comments

Comments
 (0)