Skip to content

Commit f570025

Browse files
committed
Allow StringView in certain known cases
1 parent 6554a6d commit f570025

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

src/HttpResponseWrapper.h

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -484,11 +484,13 @@ struct HttpResponseWrapper {
484484
Isolate *isolate = args.GetIsolate();
485485
auto *res = getHttpResponse<PROTOCOL>(args);
486486
if (res) {
487-
NativeString header(args.GetIsolate(), args[0]);
487+
// Optimization: writeHeader never calls JS or allocated on the GC
488+
// use zero copy string view in best case
489+
NativeString<true> header(args.GetIsolate(), args[0]);
488490
if (header.isInvalid(args)) {
489491
return;
490492
}
491-
NativeString value(args.GetIsolate(), args[1]);
493+
NativeString<true> value(args.GetIsolate(), args[1]);
492494
if (value.isInvalid(args)) {
493495
return;
494496
}

src/Utilities.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ struct Callback {
118118
}
119119
};
120120

121+
template <bool AllowStringView = false>
121122
class NativeString {
122123
char *data;
123124
size_t length;
@@ -164,10 +165,26 @@ class NativeString {
164165
length = 0;
165166
} else if (value->IsString()) {
166167
Local<String> string = Local<String>::Cast(value);
168+
169+
#if NODE_MODULE_VERSION >= 137
170+
if constexpr (AllowStringView) {
171+
172+
String::ValueView strView(isolate, string);
173+
if (strView.is_one_byte()) {
174+
length = strView.length();
175+
data = (char *) strView.data8();
176+
177+
return;
178+
}
179+
}
180+
#endif
181+
182+
// Fallback
167183
length = string->Utf8Length(isolate);
168184
data = alloc(length);
169185
allocated = true;
170186
string->WriteUtf8(isolate, data, length, nullptr, String::WriteOptions::NO_NULL_TERMINATION);
187+
171188
} else if (value->IsTypedArray()) {
172189
Local<ArrayBufferView> arrayBufferView = Local<ArrayBufferView>::Cast(value);
173190
auto contents = arrayBufferView->Buffer()->GetBackingStore();

0 commit comments

Comments
 (0)