From 87a5fac6977de2d7e434f3e2fcf4f3ec7ffd3dbf Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Wed, 20 Aug 2025 16:05:43 -0700 Subject: [PATCH] Disable postMessage optimization when string is < 256 chars (#22006) ### What does this PR do? Disable postMessage optimization when string is < 256 chars If you're going to potentially use these strings as a property or identifier, which is much more likely for short strings than long strings, we shouldn't ban atomizing them and the cost of cloning isn't so much in that case ### How did you verify your code works? --- src/bun.js/bindings/BunString.cpp | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/bun.js/bindings/BunString.cpp b/src/bun.js/bindings/BunString.cpp index 0106f02d3c..0383f1fed2 100644 --- a/src/bun.js/bindings/BunString.cpp +++ b/src/bun.js/bindings/BunString.cpp @@ -280,12 +280,17 @@ BunString toStringView(StringView view) }; } +// We don't want to ban atomiziation for tiny strings that are potentially going +// to appear as properties/identifiers in JS. So we should only do this for long +// strings that are unlikely to ever be atomized. +static constexpr unsigned int kMinCrossThreadShareableLength = 256; + bool isCrossThreadShareable(const WTF::String& string) { - if (!string.impl()) + if (string.length() < kMinCrossThreadShareableLength) return false; - auto* impl = string.impl(); + const auto* impl = string.impl(); // 1) Never share AtomStringImpl/symbols - they have special thread-unsafe behavior if (impl->isAtom() || impl->isSymbol()) @@ -306,6 +311,9 @@ Ref toCrossThreadShareable(Ref impl) if (impl->bufferOwnership() == StringImpl::BufferSubstring) return impl->isolatedCopy(); + if (impl->length() < kMinCrossThreadShareableLength) + return impl->isolatedCopy(); + // 3) Ensure we won't lazily touch hash/flags on the consumer thread // Force hash computation on this thread before sharing impl->hash(); @@ -316,8 +324,8 @@ Ref toCrossThreadShareable(Ref impl) WTF::String toCrossThreadShareable(const WTF::String& string) { - if (!string.impl()) - return string; + if (string.length() < kMinCrossThreadShareableLength) + return string.isolatedCopy(); auto* impl = string.impl();