stream: improve read() performance

PR-URL: https://github.com/nodejs/node/pull/29337
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: David Carlier <devnexen@gmail.com>
This commit is contained in:
Brian White 2019-08-27 04:12:41 -04:00
parent 25d59cf83a
commit 98b718572f
No known key found for this signature in database
GPG Key ID: 606D7358F94DA209

View File

@ -98,33 +98,31 @@ module.exports = class BufferList {
// Consumes a specified amount of characters from the buffered data. // Consumes a specified amount of characters from the buffered data.
_getString(n) { _getString(n) {
var p = this.head; let ret = '';
var c = 1; let p = this.head;
var ret = p.data; let c = 0;
n -= ret.length; do {
while (p = p.next) {
const str = p.data; const str = p.data;
const nb = (n > str.length ? str.length : n); if (n > str.length) {
if (nb === str.length) ret += str;
n -= str.length;
} else {
if (n === str.length) {
ret += str; ret += str;
else
ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c; ++c;
if (p.next) if (p.next)
this.head = p.next; this.head = p.next;
else else
this.head = this.tail = null; this.head = this.tail = null;
} else { } else {
ret += str.slice(0, n);
this.head = p; this.head = p;
p.data = str.slice(nb); p.data = str.slice(n);
} }
break; break;
} }
++c; ++c;
} } while (p = p.next);
this.length -= c; this.length -= c;
return ret; return ret;
} }
@ -132,33 +130,31 @@ module.exports = class BufferList {
// Consumes a specified amount of bytes from the buffered data. // Consumes a specified amount of bytes from the buffered data.
_getBuffer(n) { _getBuffer(n) {
const ret = Buffer.allocUnsafe(n); const ret = Buffer.allocUnsafe(n);
var p = this.head; const retLen = n;
var c = 1; let p = this.head;
p.data.copy(ret); let c = 0;
n -= p.data.length; do {
while (p = p.next) {
const buf = p.data; const buf = p.data;
const nb = (n > buf.length ? buf.length : n); if (n > buf.length) {
if (nb === buf.length) ret.set(buf, retLen - n);
ret.set(buf, ret.length - n); n -= buf.length;
else } else {
ret.set(new Uint8Array(buf.buffer, buf.byteOffset, nb), ret.length - n); if (n === buf.length) {
n -= nb; ret.set(buf, retLen - n);
if (n === 0) {
if (nb === buf.length) {
++c; ++c;
if (p.next) if (p.next)
this.head = p.next; this.head = p.next;
else else
this.head = this.tail = null; this.head = this.tail = null;
} else { } else {
ret.set(new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n);
this.head = p; this.head = p;
p.data = buf.slice(nb); p.data = buf.slice(n);
} }
break; break;
} }
++c; ++c;
} } while (p = p.next);
this.length -= c; this.length -= c;
return ret; return ret;
} }