Skip to content

Commit 9f72045

Browse files
committed
stream: add fast-path for readable streams
1 parent 7675749 commit 9f72045

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const Readable = require('stream').Readable;
5+
6+
const BASE = 'hello world\n\n';
7+
8+
const bench = common.createBenchmark(main, {
9+
encoding: ['utf-8', 'latin1'],
10+
len: [256, 512, 1024 * 16],
11+
op: ['unshift', 'push'],
12+
n: [1e3]
13+
});
14+
15+
function main({ n, encoding, len, op }) {
16+
const b = BASE.repeat(len);
17+
const s = new Readable({
18+
objectMode: false,
19+
});
20+
21+
bench.start();
22+
switch (op) {
23+
case 'unshift': {
24+
for (let i = 0; i < n; i++)
25+
s.unshift(b, encoding);
26+
break;
27+
}
28+
case 'push': {
29+
for (let i = 0; i < n; i++)
30+
s.push(b, encoding);
31+
break;
32+
}
33+
}
34+
bench.end(n);
35+
}

lib/internal/streams/readable.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ const EE = require('events');
4242
const { Stream, prependListener } = require('internal/streams/legacy');
4343
const { Buffer } = require('buffer');
4444

45+
const { TextEncoder } = require('internal/encoding');
46+
4547
const {
4648
addAbortSignal,
4749
} = require('internal/streams/add-abort-signal');
@@ -73,6 +75,9 @@ const kPaused = Symbol('kPaused');
7375

7476
const { StringDecoder } = require('string_decoder');
7577
const from = require('internal/streams/from');
78+
const { normalizeEncoding } = require('internal/util');
79+
const { FastBuffer } = require('internal/buffer');
80+
const encoder = new TextEncoder();
7681

7782
ObjectSetPrototypeOf(Readable.prototype, Stream.prototype);
7883
ObjectSetPrototypeOf(Readable, Stream);
@@ -251,9 +256,17 @@ function readableAddChunk(stream, chunk, encoding, addToFront) {
251256
if (addToFront && state.encoding) {
252257
// When unshifting, if state.encoding is set, we have to save
253258
// the string in the BufferList with the state encoding.
259+
254260
chunk = Buffer.from(chunk, encoding).toString(state.encoding);
255261
} else {
256-
chunk = Buffer.from(chunk, encoding);
262+
const enc = normalizeEncoding(encoding);
263+
264+
if (enc === 'utf8') {
265+
const uint8 = encoder.encode(chunk);
266+
chunk = new FastBuffer(uint8, 0, uint8.length);
267+
} else {
268+
chunk = Buffer.from(chunk, encoding);
269+
}
257270
encoding = '';
258271
}
259272
}

0 commit comments

Comments
 (0)