Skip to content

Commit

Permalink
buffer: optimize byteLength for short strings
Browse files Browse the repository at this point in the history
PR-URL: #54345
  • Loading branch information
ronag committed Aug 13, 2024
1 parent 298ff4f commit 110e88b
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/node_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
#include "v8-fast-api-calls.h"
#include "v8.h"

#include <bit>
#include <climits>
#include <cstring>
#include "nbytes.h"
Expand Down Expand Up @@ -752,12 +753,25 @@ uint32_t FastByteLengthUtf8(Local<Value> 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<const uint8_t*>(source.data);
for (uint32_t i = 0; i < length; ++i) {
const auto data = reinterpret_cast<const uint8_t*>(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;
}

Expand Down

0 comments on commit 110e88b

Please sign in to comment.