Skip to content

Commit d82ecb9

Browse files
mscdexBridgeAR
authored andcommitted
stream: improve read() performance
PR-URL: #29337 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: David Carlier <devnexen@gmail.com>
1 parent 1ee0683 commit d82ecb9

File tree

1 file changed

+25
-29
lines changed

1 file changed

+25
-29
lines changed

lib/internal/streams/buffer_list.js

Lines changed: 25 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -98,67 +98,63 @@ module.exports = class BufferList {
9898

9999
// Consumes a specified amount of characters from the buffered data.
100100
_getString(n) {
101-
var p = this.head;
102-
var c = 1;
103-
var ret = p.data;
104-
n -= ret.length;
105-
while (p = p.next) {
101+
let ret = '';
102+
let p = this.head;
103+
let c = 0;
104+
do {
106105
const str = p.data;
107-
const nb = (n > str.length ? str.length : n);
108-
if (nb === str.length)
106+
if (n > str.length) {
109107
ret += str;
110-
else
111-
ret += str.slice(0, n);
112-
n -= nb;
113-
if (n === 0) {
114-
if (nb === str.length) {
108+
n -= str.length;
109+
} else {
110+
if (n === str.length) {
111+
ret += str;
115112
++c;
116113
if (p.next)
117114
this.head = p.next;
118115
else
119116
this.head = this.tail = null;
120117
} else {
118+
ret += str.slice(0, n);
121119
this.head = p;
122-
p.data = str.slice(nb);
120+
p.data = str.slice(n);
123121
}
124122
break;
125123
}
126124
++c;
127-
}
125+
} while (p = p.next);
128126
this.length -= c;
129127
return ret;
130128
}
131129

132130
// Consumes a specified amount of bytes from the buffered data.
133131
_getBuffer(n) {
134132
const ret = Buffer.allocUnsafe(n);
135-
var p = this.head;
136-
var c = 1;
137-
p.data.copy(ret);
138-
n -= p.data.length;
139-
while (p = p.next) {
133+
const retLen = n;
134+
let p = this.head;
135+
let c = 0;
136+
do {
140137
const buf = p.data;
141-
const nb = (n > buf.length ? buf.length : n);
142-
if (nb === buf.length)
143-
ret.set(buf, ret.length - n);
144-
else
145-
ret.set(new Uint8Array(buf.buffer, buf.byteOffset, nb), ret.length - n);
146-
n -= nb;
147-
if (n === 0) {
148-
if (nb === buf.length) {
138+
if (n > buf.length) {
139+
ret.set(buf, retLen - n);
140+
n -= buf.length;
141+
} else {
142+
if (n === buf.length) {
143+
ret.set(buf, retLen - n);
149144
++c;
150145
if (p.next)
151146
this.head = p.next;
152147
else
153148
this.head = this.tail = null;
154149
} else {
150+
ret.set(new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n);
155151
this.head = p;
156-
p.data = buf.slice(nb);
152+
p.data = buf.slice(n);
157153
}
158154
break;
159155
}
160156
++c;
161-
}
157+
} while (p = p.next);
162158
this.length -= c;
163159
return ret;
164160
}

0 commit comments

Comments
 (0)