From 8438fdda8add54b2ef4cb2c13d465eee631bf819 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 22 Jul 2026 06:39:26 +0000 Subject: [PATCH 1/3] Headers: hash-index uncommon names past 64 entries so per-name lookup stays O(1) HTTPHeaderMap stored uncommon header names in a Vector scanned linearly on every get/set/append/has/delete, so N distinct names cost O(N) per operation and O(N^2) to build or read once. Add a lazily-built ASCIICaseInsensitiveHash map from name to vector index, constructed only once the vector passes 64 entries; below that the existing linear scan runs unchanged. The index aliases the String already held by each vector entry, so it costs one bucket per name rather than a second copy. Release build, N distinct uncommon names, append each then get each: N=50 16.6us -> 15.8us N=255 354us -> 65.5us N=1000 4.5ms -> 233us N=12k 868ms -> 6ms --- src/jsc/bindings/webcore/HTTPHeaderMap.cpp | 89 +++++++++++++++------- src/jsc/bindings/webcore/HTTPHeaderMap.h | 38 ++++++++- test/js/web/fetch/headers.test.ts | 78 +++++++++++++++++++ 3 files changed, 175 insertions(+), 30 deletions(-) diff --git a/src/jsc/bindings/webcore/HTTPHeaderMap.cpp b/src/jsc/bindings/webcore/HTTPHeaderMap.cpp index 4ce2c1b0fcb3..de653441fc8f 100644 --- a/src/jsc/bindings/webcore/HTTPHeaderMap.cpp +++ b/src/jsc/bindings/webcore/HTTPHeaderMap.cpp @@ -76,10 +76,43 @@ String lowercaseHeaderName(const String& name) return result; } +// Linear scan stays faster than hashing for the handful-of-headers case that +// dominates real traffic. Past this many distinct uncommon names, build a hash +// index so get/set/append/has stay O(1) instead of degrading to O(N) per call. +static constexpr unsigned uncommonHeadersIndexThreshold = 64; + HTTPHeaderMap::HTTPHeaderMap() { } +size_t HTTPHeaderMap::findUncommonHeaderIndex(const StringView name) const +{ + if (!m_uncommonHeadersIndex) { + unsigned size = m_uncommonHeaders.size(); + if (size <= uncommonHeadersIndexThreshold) { + return m_uncommonHeaders.findIf([&](auto& header) { + return equalIgnoringASCIICase(header.key, name); + }); + } + auto index = makeUnique(); + index->reserveInitialCapacity(size); + for (unsigned i = 0; i < size; ++i) + index->add(m_uncommonHeaders[i].key, i); + m_uncommonHeadersIndex = WTF::move(index); + } + + auto it = m_uncommonHeadersIndex->find(name); + return it != m_uncommonHeadersIndex->end() ? it->value : notFound; +} + +void HTTPHeaderMap::appendUncommonHeader(const String& name, const String& value) +{ + unsigned index = m_uncommonHeaders.size(); + m_uncommonHeaders.append(UncommonHeader { name, value }); + if (m_uncommonHeadersIndex) + m_uncommonHeadersIndex->add(m_uncommonHeaders[index].key, index); +} + HTTPHeaderMap HTTPHeaderMap::isolatedCopy() const& { HTTPHeaderMap map; @@ -112,6 +145,8 @@ size_t HTTPHeaderMap::memoryCost() const size_t cost = m_commonHeaders.size() * sizeof(CommonHeader); cost += m_uncommonHeaders.size() * sizeof(UncommonHeader); cost += m_setCookieHeaders.size() * sizeof(String); + if (m_uncommonHeadersIndex) + cost += m_uncommonHeadersIndex->capacity() * (sizeof(String) + sizeof(unsigned)); for (auto& header : m_commonHeaders) cost += header.value.sizeInBytes(); @@ -128,9 +163,7 @@ size_t HTTPHeaderMap::memoryCost() const String HTTPHeaderMap::getUncommonHeader(const StringView name) const { - auto index = m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); return index != notFound ? m_uncommonHeaders[index].value : String(); } @@ -168,36 +201,30 @@ void HTTPHeaderMap::set(const String& name, const String& value) void HTTPHeaderMap::setUncommonHeader(const String& name, const String& value) { - auto index = m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); if (index == notFound) - m_uncommonHeaders.append(UncommonHeader { name, value }); + appendUncommonHeader(name, value); else m_uncommonHeaders[index].value = value; } void HTTPHeaderMap::addUncommonHeader(const String& name, const String& value) { - auto index = m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); if (index == notFound) - m_uncommonHeaders.append(UncommonHeader { name, value }); + appendUncommonHeader(name, value); else m_uncommonHeaders[index].value = makeString(m_uncommonHeaders[index].value, ", "_s, value); } void HTTPHeaderMap::addUncommonHeaderCloneName(const StringView name, const String& value) { - auto index = m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); if (index == notFound) { std::span ptr; auto nameCopy = WTF::String::createUninitialized(name.length(), ptr); memcpy(ptr.data(), name.span8().data(), name.length()); - m_uncommonHeaders.append(UncommonHeader { nameCopy, value }); + appendUncommonHeader(nameCopy, value); } else m_uncommonHeaders[index].value = makeString(m_uncommonHeaders[index].value, ", "_s, value); } @@ -209,11 +236,9 @@ void HTTPHeaderMap::add(const String& name, const String& value) add(headerName, value); return; } - auto index = m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); if (index == notFound) - m_uncommonHeaders.append(UncommonHeader { name, value }); + appendUncommonHeader(name, value); else m_uncommonHeaders[index].value = makeString(m_uncommonHeaders[index].value, ", "_s, value); } @@ -229,7 +254,7 @@ void HTTPHeaderMap::append(const String& name, const String& value) else m_commonHeaders.append(CommonHeader { headerName, value }); } else { - m_uncommonHeaders.append(UncommonHeader { name, value }); + appendUncommonHeader(name, value); } } @@ -248,9 +273,7 @@ bool HTTPHeaderMap::contains(const StringView name) const if (findHTTPHeaderName(name, headerName)) return contains(headerName); - return m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }) != notFound; + return findUncommonHeaderIndex(name) != notFound; } bool HTTPHeaderMap::remove(const StringView name) @@ -270,9 +293,19 @@ bool HTTPHeaderMap::removeUncommonHeader(const StringView name) ASSERT(!findHTTPHeaderName(name, headerName)); #endif - return m_uncommonHeaders.removeFirstMatching([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); + if (index == notFound) + return false; + + m_uncommonHeaders.removeAt(index); + if (m_uncommonHeadersIndex) { + m_uncommonHeadersIndex->remove(name); + for (auto& entry : *m_uncommonHeadersIndex) { + if (entry.value > index) + --entry.value; + } + } + return true; } String HTTPHeaderMap::get(HTTPHeaderName name) const @@ -313,9 +346,7 @@ HTTPHeaderMap::HeaderIndex HTTPHeaderMap::indexOf(HTTPHeaderName name) const HTTPHeaderMap::HeaderIndex HTTPHeaderMap::indexOf(const String& name) const { - auto index = m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); return (HeaderIndex) { .index = index, .isCommon = false }; } diff --git a/src/jsc/bindings/webcore/HTTPHeaderMap.h b/src/jsc/bindings/webcore/HTTPHeaderMap.h index 4f617d07d475..618452e426aa 100644 --- a/src/jsc/bindings/webcore/HTTPHeaderMap.h +++ b/src/jsc/bindings/webcore/HTTPHeaderMap.h @@ -27,7 +27,10 @@ #pragma once #include "HTTPHeaderNames.h" +#include #include +#include +#include #include namespace WebCore { @@ -170,6 +173,23 @@ class HTTPHeaderMap { WEBCORE_EXPORT HTTPHeaderMap(); + HTTPHeaderMap(const HTTPHeaderMap &other) + : m_commonHeaders(other.m_commonHeaders) + , m_uncommonHeaders(other.m_uncommonHeaders) + , m_setCookieHeaders(other.m_setCookieHeaders) + { + } + HTTPHeaderMap(HTTPHeaderMap &&) = default; + HTTPHeaderMap &operator=(const HTTPHeaderMap &other) + { + m_commonHeaders = other.m_commonHeaders; + m_uncommonHeaders = other.m_uncommonHeaders; + m_setCookieHeaders = other.m_setCookieHeaders; + m_uncommonHeadersIndex = nullptr; + return *this; + } + HTTPHeaderMap &operator=(HTTPHeaderMap &&) = default; + // Gets a copy of the data suitable for passing to another thread. WEBCORE_EXPORT HTTPHeaderMap isolatedCopy() const &; WEBCORE_EXPORT HTTPHeaderMap isolatedCopy() &&; @@ -181,6 +201,7 @@ class HTTPHeaderMap { { m_commonHeaders.clear(); m_uncommonHeaders.clear(); + m_uncommonHeadersIndex = nullptr; } void shrinkToFit() @@ -233,7 +254,11 @@ class HTTPHeaderMap { const CommonHeadersVector &commonHeaders() const { return m_commonHeaders; } const UncommonHeadersVector &uncommonHeaders() const { return m_uncommonHeaders; } CommonHeadersVector &commonHeaders() { return m_commonHeaders; } - UncommonHeadersVector &uncommonHeaders() { return m_uncommonHeaders; } + UncommonHeadersVector &uncommonHeaders() + { + m_uncommonHeadersIndex = nullptr; + return m_uncommonHeaders; + } Vector &getSetCookieHeaders() { return m_setCookieHeaders; } const_iterator begin() const { return const_iterator(*this, m_commonHeaders.begin(), m_uncommonHeaders.begin(), m_setCookieHeaders.begin()); } @@ -274,11 +299,22 @@ class HTTPHeaderMap { void addUncommonHeaderCloneName(const StringView name, const String &value); private: + using UncommonHeadersIndex = HashMap; + WEBCORE_EXPORT String getUncommonHeader(const StringView name) const; + size_t findUncommonHeaderIndex(const StringView name) const; + void appendUncommonHeader(const String &name, const String &value); + CommonHeadersVector m_commonHeaders; UncommonHeadersVector m_uncommonHeaders; Vector m_setCookieHeaders; + + // Lazily built once m_uncommonHeaders grows past the point where a linear + // scan per lookup becomes quadratic in aggregate. The stored keys alias the + // String already held by the vector entry, so the index costs one bucket + // per name rather than a second copy of the name. + mutable std::unique_ptr m_uncommonHeadersIndex; }; template diff --git a/test/js/web/fetch/headers.test.ts b/test/js/web/fetch/headers.test.ts index b514a241674c..f1aff88df3b7 100644 --- a/test/js/web/fetch/headers.test.ts +++ b/test/js/web/fetch/headers.test.ts @@ -582,6 +582,84 @@ describe("Headers", () => { }); }); }); + describe("many distinct uncommon names", () => { + // Past a small threshold, HTTPHeaderMap builds a hash index over the + // uncommon-header vector so per-name lookups stay O(1). Exercise every + // mutation/lookup path across that boundary, including after delete() + // has shifted vector entries, so a stale index would return the wrong + // slot. + test("stays correct across get/has/set/append/delete", () => { + const N = 200; + const name = (i: number) => (i % 2 === 0 ? "x-" : "X-") + i; + const h = new Headers(); + for (let i = 0; i < N; i++) h.append(name(i), "v" + i); + expect(h.count).toBe(N); + + for (let i = 0; i < N; i++) { + expect(h.get("x-" + i)).toBe("v" + i); + expect(h.get("X-" + i)).toBe("v" + i); + expect(h.has("x-" + i)).toBe(true); + } + expect(h.get("x-" + N)).toBeNull(); + expect(h.has("x-" + N)).toBe(false); + + for (let i = 0; i < N; i += 3) h.set("X-" + i, "s" + i); + for (let i = 1; i < N; i += 3) h.append("x-" + i, "a" + i); + for (let i = 2; i < N; i += 3) h.delete("x-" + i); + for (let i = 0; i < N; i++) { + if (i % 3 === 0) expect(h.get("x-" + i)).toBe("s" + i); + else if (i % 3 === 1) expect(h.get("x-" + i)).toBe("v" + i + ", a" + i); + else { + expect(h.get("x-" + i)).toBeNull(); + expect(h.has("x-" + i)).toBe(false); + } + } + + const copy = new Headers(h); + for (let i = 0; i < N; i += 3) expect(copy.get("x-" + i)).toBe("s" + i); + + h.set("x-late", "z"); + h.append("x-late", "zz"); + expect(h.get("X-Late")).toBe("z, zz"); + }); + + // get()/has() on an uncommon name used to scan the whole vector, so the + // cost of a single lookup grew with the number of distinct names. Probe + // the last N names of an N-entry map and an 8N-entry map: if the lookup + // scales with entry count the second run is ~8x slower; with the hash + // index it is O(1) and both runs take the same time. The ratio is + // self-calibrating across release/debug/ASAN builds so no absolute time + // budget is needed. + test("per-name lookup is independent of distinct-name count", () => { + const N = 1500; + + const small = new Headers(); + for (let i = 0; i < N; i++) small.append("x-" + i, "v"); + const smallProbe: string[] = []; + for (let i = 0; i < N; i++) smallProbe.push("x-" + (N - 1 - i)); + + const large = new Headers(); + for (let i = 0; i < N * 8; i++) large.append("x-" + i, "v"); + const largeProbe: string[] = []; + for (let i = 0; i < N; i++) largeProbe.push("x-" + (N * 8 - 1 - i)); + + const time = (h: Headers, names: string[]) => { + const t = performance.now(); + for (let i = 0; i < N; i++) h.get(names[i]); + return performance.now() - t; + }; + const best = (h: Headers, names: string[]) => Math.min(time(h, names), time(h, names), time(h, names)); + + time(small, smallProbe); + time(large, largeProbe); + const tSmall = best(small, smallProbe); + const tLarge = best(large, largeProbe); + + expect(small.get("x-0")).toBe("v"); + expect(large.get("x-" + (N * 8 - 1))).toBe("v"); + expect(tLarge / Math.max(tSmall, 1)).toBeLessThan(3); + }); + }); describe("count", () => { // @ts-ignore const it = typeof new Headers()?.count !== "undefined" ? test : test.skip; From 5f479451f89c6ebc1836b8db3f24670203b35add Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 22 Jul 2026 06:47:32 +0000 Subject: [PATCH 2/3] Drop mutable uncommonHeaders() accessor; FetchHeaders::fill copies the map directly The only caller of the non-const accessor was FetchHeaders::fill filling an empty map, which is now a straight copy of the source HTTPHeaderMap. Removing the accessor means no caller can hold a mutable vector reference across a lookup that rebuilds the index. Also correct the linear-scan ratio in the test comment (probing the last N of an 8N-entry map averages ~7.5N scan depth vs ~N/2 for the N-entry map, so ~15x, not 8x). --- src/jsc/bindings/webcore/FetchHeaders.cpp | 6 +----- src/jsc/bindings/webcore/HTTPHeaderMap.h | 5 ----- test/js/web/fetch/headers.test.ts | 10 +++++----- 3 files changed, 6 insertions(+), 15 deletions(-) diff --git a/src/jsc/bindings/webcore/FetchHeaders.cpp b/src/jsc/bindings/webcore/FetchHeaders.cpp index 016bd82c4977..033903e5e8f8 100644 --- a/src/jsc/bindings/webcore/FetchHeaders.cpp +++ b/src/jsc/bindings/webcore/FetchHeaders.cpp @@ -213,11 +213,7 @@ ExceptionOr FetchHeaders::fill(const Init& headerInit) ExceptionOr FetchHeaders::fill(const FetchHeaders& otherHeaders) { if (this->size() == 0) { - HTTPHeaderMap headers; - headers.commonHeaders().appendVector(otherHeaders.m_headers.commonHeaders()); - headers.uncommonHeaders().appendVector(otherHeaders.m_headers.uncommonHeaders()); - headers.getSetCookieHeaders().appendVector(otherHeaders.m_headers.getSetCookieHeaders()); - setInternalHeaders(WTF::move(headers)); + m_headers = otherHeaders.m_headers; m_updateCounter++; return {}; } diff --git a/src/jsc/bindings/webcore/HTTPHeaderMap.h b/src/jsc/bindings/webcore/HTTPHeaderMap.h index 618452e426aa..fd5a469da158 100644 --- a/src/jsc/bindings/webcore/HTTPHeaderMap.h +++ b/src/jsc/bindings/webcore/HTTPHeaderMap.h @@ -254,11 +254,6 @@ class HTTPHeaderMap { const CommonHeadersVector &commonHeaders() const { return m_commonHeaders; } const UncommonHeadersVector &uncommonHeaders() const { return m_uncommonHeaders; } CommonHeadersVector &commonHeaders() { return m_commonHeaders; } - UncommonHeadersVector &uncommonHeaders() - { - m_uncommonHeadersIndex = nullptr; - return m_uncommonHeaders; - } Vector &getSetCookieHeaders() { return m_setCookieHeaders; } const_iterator begin() const { return const_iterator(*this, m_commonHeaders.begin(), m_uncommonHeaders.begin(), m_setCookieHeaders.begin()); } diff --git a/test/js/web/fetch/headers.test.ts b/test/js/web/fetch/headers.test.ts index f1aff88df3b7..e926d0d03da1 100644 --- a/test/js/web/fetch/headers.test.ts +++ b/test/js/web/fetch/headers.test.ts @@ -625,11 +625,11 @@ describe("Headers", () => { // get()/has() on an uncommon name used to scan the whole vector, so the // cost of a single lookup grew with the number of distinct names. Probe - // the last N names of an N-entry map and an 8N-entry map: if the lookup - // scales with entry count the second run is ~8x slower; with the hash - // index it is O(1) and both runs take the same time. The ratio is - // self-calibrating across release/debug/ASAN builds so no absolute time - // budget is needed. + // the last N names of an N-entry map and an 8N-entry map: with a linear + // scan the second run does ~15x the work (average scan depth ~7.5N vs + // ~N/2); with the hash index it is O(1) and both runs take the same time. + // The ratio self-calibrates across release/debug/ASAN builds so no + // absolute time budget is needed. test("per-name lookup is independent of distinct-name count", () => { const N = 1500; From c7cfa47ee03539b0750a200d562b2c70e314700c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 22 Jul 2026 07:06:32 +0000 Subject: [PATCH 3/3] headers test: size probe loop so the baseline clears 1ms on release At N=1500 gets the release-build baseline was ~0.3ms, so the 1ms floor turned the ratio assertion into an absolute tLarge < 3ms bound. Cycle 20000 gets through the same N names instead; the release baseline is now ~1.3ms, the floor is gone, and the ratio self-calibrates on every build. best-of-2 absorbs single scheduler blips. --- test/js/web/fetch/headers.test.ts | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/test/js/web/fetch/headers.test.ts b/test/js/web/fetch/headers.test.ts index e926d0d03da1..a69583ea132b 100644 --- a/test/js/web/fetch/headers.test.ts +++ b/test/js/web/fetch/headers.test.ts @@ -628,10 +628,12 @@ describe("Headers", () => { // the last N names of an N-entry map and an 8N-entry map: with a linear // scan the second run does ~15x the work (average scan depth ~7.5N vs // ~N/2); with the hash index it is O(1) and both runs take the same time. - // The ratio self-calibrates across release/debug/ASAN builds so no - // absolute time budget is needed. + // ITER is sized so the baseline clears 1ms on a release build and the + // ratio self-calibrates across release/debug/ASAN without an absolute + // time budget. test("per-name lookup is independent of distinct-name count", () => { const N = 1500; + const ITER = 20000; const small = new Headers(); for (let i = 0; i < N; i++) small.append("x-" + i, "v"); @@ -645,19 +647,16 @@ describe("Headers", () => { const time = (h: Headers, names: string[]) => { const t = performance.now(); - for (let i = 0; i < N; i++) h.get(names[i]); + for (let i = 0; i < ITER; i++) h.get(names[i % N]); return performance.now() - t; }; - const best = (h: Headers, names: string[]) => Math.min(time(h, names), time(h, names), time(h, names)); - time(small, smallProbe); - time(large, largeProbe); - const tSmall = best(small, smallProbe); - const tLarge = best(large, largeProbe); + const tSmall = Math.min(time(small, smallProbe), time(small, smallProbe)); + const tLarge = Math.min(time(large, largeProbe), time(large, largeProbe)); expect(small.get("x-0")).toBe("v"); expect(large.get("x-" + (N * 8 - 1))).toBe("v"); - expect(tLarge / Math.max(tSmall, 1)).toBeLessThan(3); + expect(tLarge / tSmall).toBeLessThan(3); }); }); describe("count", () => {