Skip to content

Commit af328a2

Browse files
committed
buffer: optimize writing short strings
PR-URL: nodejs#54310
1 parent 298ff4f commit af328a2

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

benchmark/buffers/buffer-write-string.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ const bench = common.createBenchmark(main, {
66
'', 'utf8', 'ascii', 'hex', 'utf16le', 'latin1',
77
],
88
args: [ '', 'offset', 'offset+length' ],
9-
len: [2048],
9+
len: [1, 8, 16, 2048],
1010
n: [1e6],
1111
});
1212

lib/buffer.js

+26-3
Original file line numberDiff line numberDiff line change
@@ -1082,10 +1082,10 @@ function _fill(buf, value, offset, end, encoding) {
10821082
Buffer.prototype.write = function write(string, offset, length, encoding) {
10831083
// Buffer#write(string);
10841084
if (offset === undefined) {
1085-
return this.utf8Write(string, 0, this.length);
1086-
}
1085+
offset = 0;
1086+
length = this.length;
10871087
// Buffer#write(string, encoding)
1088-
if (length === undefined && typeof offset === 'string') {
1088+
} else if (length === undefined && typeof offset === 'string') {
10891089
encoding = offset;
10901090
length = this.length;
10911091
offset = 0;
@@ -1108,6 +1108,29 @@ Buffer.prototype.write = function write(string, offset, length, encoding) {
11081108
}
11091109
}
11101110

1111+
const len = string?.length;
1112+
if (
1113+
len <= 16 &&
1114+
len <= length &&
1115+
(!encoding || encoding === 'ascii' || encoding === 'utf8') &&
1116+
typeof string === 'string'
1117+
) {
1118+
let n = 0;
1119+
while (true) {
1120+
const code = StringPrototypeCharCodeAt(string, n);
1121+
if (code >= 128) {
1122+
break;
1123+
}
1124+
1125+
this[offset + n] = code;
1126+
n++;
1127+
1128+
if (n === len) {
1129+
return len;
1130+
}
1131+
}
1132+
}
1133+
11111134
if (!encoding)
11121135
return this.utf8Write(string, offset, length);
11131136

0 commit comments

Comments
 (0)