Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
src: improve StringBytes::Encode perf on UTF8
Co-authored-by: Gürgün Dayıoğlu <hey@gurgun.day>
  • Loading branch information
ChALkeR and gurgunday committed Jan 18, 2026
commit d4f04603f3a8131ad6ed7764ea6e88c4e975fe63
2 changes: 2 additions & 0 deletions src/encoding_binding.cc
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,8 @@ void BindingData::DecodeUTF8(const FunctionCallbackInfo<Value>& args) {
return node::THROW_ERR_ENCODING_INVALID_ENCODED_DATA(
env->isolate(), "The encoded data was not valid for encoding utf-8");
}

// TODO(chalker): save on utf8 validity recheck in StringBytes::Encode()
Comment thread
ChALkeR marked this conversation as resolved.
}

if (length == 0) return args.GetReturnValue().SetEmptyString();
Expand Down
18 changes: 18 additions & 0 deletions src/string_bytes.cc
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,24 @@ MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
return ExternOneByteString::NewFromCopy(isolate, buf, buflen);
}

if (simdutf::validate_utf8(buf, buflen)) {
// We know that we are non-ASCII (and are unlikely Latin1), use 2-byte
// In the most likely case of valid UTF-8, we can use this fast impl
size_t u16size = simdutf::utf16_length_from_utf8(buf, buflen);
Comment thread
ChALkeR marked this conversation as resolved.
if (u16size > static_cast<size_t>(v8::String::kMaxLength)) {
isolate->ThrowException(ERR_STRING_TOO_LONG(isolate));
return MaybeLocal<Value>();
}
uint16_t* dst = node::UncheckedMalloc<uint16_t>(u16size);
Comment thread
ChALkeR marked this conversation as resolved.
if (u16size != 0 && dst == nullptr) {
THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
return MaybeLocal<Value>();
}
size_t utf16len = simdutf::convert_valid_utf8_to_utf16(
buf, buflen, reinterpret_cast<char16_t*>(dst));
return ExternTwoByteString::New(isolate, dst, utf16len);
}

val =
String::NewFromUtf8(isolate, buf, v8::NewStringType::kNormal, buflen);
Local<String> str;
Expand Down
Loading