From ada198bee0f88c2c03c9c380a4373d80714fd524 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Thu, 17 Jul 2025 00:03:18 +0200 Subject: [PATCH] LibJS: Add fast path for TypedArrayPrototype.copyWithin() This can be a simple memmove() in the most common cases. Shaves 500ms of load time off of https://terminal.shop/api --- .../LibJS/Runtime/TypedArrayPrototype.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp b/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp index 550351fcebc..471c2b98085 100644 --- a/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp +++ b/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp @@ -383,6 +383,25 @@ JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::copy_within) direction = 1; } + // OPTIMIZATION: Fast path for non-shared ArrayBuffers that are not detached and have enough space to perform the copy with memmove. + if (!buffer->is_shared_array_buffer()) { + Checked from_end = from_byte_index; + from_end += count_bytes; + Checked to_end = to_byte_index; + to_end += count_bytes; + + if (!from_end.has_overflow() + && !to_end.has_overflow() + && from_end.value() <= buffer_byte_limit + && to_end.value() <= buffer_byte_limit) { + auto* base = buffer->buffer().data(); + void const* src = base + from_byte_index; + void* dst = base + to_byte_index; + memmove(dst, src, count_bytes); + return typed_array; + } + } + // n. Repeat, while countBytes > 0, while (count_bytes > 0) { // i. If fromByteIndex < bufferByteLimit and toByteIndex < bufferByteLimit, then