Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

buffer: optimize byteLength for short strings #54345

Merged
merged 1 commit into from
Aug 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 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 <stdint.h>
#include <climits>
#include <cstring>
#include "nbytes.h"
Expand Down Expand Up @@ -752,13 +753,40 @@ 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) {
result += (data[i] >> 7);
const auto input = reinterpret_cast<const uint8_t*>(source.data);

uint32_t answer = length;
uint32_t i = 0;

auto pop = [](uint64_t v) {
return static_cast<size_t>(((v >> 7) & UINT64_C(0x0101010101010101)) *
UINT64_C(0x0101010101010101) >>
56);
};

for (; i + 32 <= length; i += 32) {
uint64_t v;
memcpy(&v, input + i, 8);
answer += pop(v);
memcpy(&v, input + i + 8, 8);
answer += pop(v);
memcpy(&v, input + i + 16, 8);
answer += pop(v);
memcpy(&v, input + i + 24, 8);
answer += pop(v);
}
Comment on lines +769 to +779
Copy link
Member

@BridgeAR BridgeAR Aug 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this really improving the performance? I am surprised that unrolling the loop is beneficial compared to just the lines right afterwards. I would expect the compiler to optimize things like that.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just took from simdutf @lemire wdyt?

for (; i + 8 <= length; i += 8) {
uint64_t v;
memcpy(&v, input + i, 8);
answer += pop(v);
}
return result;
for (; i + 1 <= length; i += 1) {
answer += input[i] >> 7;
}

return answer;
}

static v8::CFunction fast_byte_length_utf8(
Expand Down
Loading