From 17e2f751c5804845631cb3ee3da048b66b31ed0a Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Tue, 27 Feb 2024 11:00:44 -0500 Subject: [PATCH] LibJS: Add an explicit DataBlock::size method This avoids visiting the underlying buffer twice from ArrayBuffer's byte_length. On https://cyxx.github.io/another_js, this reduces the runtime of IsValidIntegerIndex from 9.9% to 8.9%. --- Userland/Libraries/LibJS/Runtime/ArrayBuffer.h | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Userland/Libraries/LibJS/Runtime/ArrayBuffer.h b/Userland/Libraries/LibJS/Runtime/ArrayBuffer.h index ab861d9f21..9f3a240afa 100644 --- a/Userland/Libraries/LibJS/Runtime/ArrayBuffer.h +++ b/Userland/Libraries/LibJS/Runtime/ArrayBuffer.h @@ -42,6 +42,14 @@ struct DataBlock { } ByteBuffer const& buffer() const { return const_cast(this)->buffer(); } + size_t size() const + { + return byte_buffer.visit( + [](Empty) -> size_t { return 0u; }, + [](ByteBuffer const& buffer) { return buffer.size(); }, + [](ByteBuffer const* buffer) { return buffer->size(); }); + } + Variant byte_buffer; Shared is_shared = { Shared::No }; }; @@ -57,13 +65,7 @@ public: virtual ~ArrayBuffer() override = default; - size_t byte_length() const - { - if (is_detached()) - return 0; - - return m_data_block.buffer().size(); - } + size_t byte_length() const { return m_data_block.size(); } // [[ArrayBufferData]] ByteBuffer& buffer() { return m_data_block.buffer(); }