Skip to content

Commit 28679d7

Browse files
thisalihassanaduh95
authored andcommitted
src: use stack allocation for small string encoding
Use stack-allocated buffers in StringBytes::Encode() for small inputs instead of heap-allocating via UncheckedMalloc for every call. Refs: nodejs/performance#194 PR-URL: #62431 Refs: nodejs/performance#194 Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
1 parent 518b578 commit 28679d7

1 file changed

Lines changed: 84 additions & 81 deletions

File tree

src/string_bytes.cc

Lines changed: 84 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -145,12 +145,49 @@ class ExternString: public ResourceType {
145145
size_t length_;
146146
};
147147

148+
typedef ExternString<String::ExternalOneByteStringResource, char>
149+
ExternOneByteString;
150+
typedef ExternString<String::ExternalStringResource, uint16_t>
151+
ExternTwoByteString;
152+
153+
template <typename EncodeFn>
154+
static MaybeLocal<Value> EncodeOneByteString(Isolate* isolate,
155+
size_t length,
156+
EncodeFn encode) {
157+
// 512B stack threshold: covers common small outputs (hex SHA-256/512, UUIDs).
158+
// Larger thresholds were benchmarked
159+
MaybeStackBuffer<char, 512> buf(length);
160+
encode(buf.out());
161+
// Copy stack-backed data, but release heap-backed storage to V8.
162+
if (buf.IsAllocated()) {
163+
char* data = buf.out();
164+
buf.Release();
165+
return ExternOneByteString::New(isolate, data, length);
166+
}
167+
return String::NewFromOneByte(isolate,
168+
reinterpret_cast<const uint8_t*>(buf.out()),
169+
v8::NewStringType::kNormal,
170+
static_cast<int>(length));
171+
}
148172

149-
typedef ExternString<String::ExternalOneByteStringResource,
150-