From 110e88b19166bd7ae1984866ad57259a12f8789a Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Mon, 12 Aug 2024 23:10:08 +0200 Subject: [PATCH] buffer: optimize byteLength for short strings PR-URL: https://github.com/nodejs/node/pull/54345 --- src/node_buffer.cc | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 6e141b974131cc..b46864a3a74f92 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -35,6 +35,7 @@ #include "v8-fast-api-calls.h" #include "v8.h" +#include #include #include #include "nbytes.h" @@ -752,12 +753,25 @@ uint32_t FastByteLengthUtf8(Local receiver, if (source.length > 128) { return simdutf::utf8_length_from_latin1(source.data, source.length); } + uint32_t length = source.length; uint32_t result = length; - const uint8_t* data = reinterpret_cast(source.data); - for (uint32_t i = 0; i < length; ++i) { + const auto data = reinterpret_cast(source.data); + + uint32_t i = 0; + const auto length8 = length & ~0x7; + while (i < length8) { + uint64_t x; + memcpy(&x, data + i, sizeof(uint64_t)); + result += std::popcount(x & 0x8080808080808080); + i += 8; + } + + while (i < length) { result += (data[i] >> 7); + i++; } + return result; }