Truly independent web browser
LibWeb: Evict selector queries without scanning the whole cache
Andreas Klingc7b47f782384
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 4f8997e7ac9..1b46585b81f 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -12469,11 +12469,9 @@ RefPtr<SelectorQuery const> Document::selector_query_for(Utf16View selector_text{static constexpr size_t MAX_SELECTOR_QUERY_CACHE_SIZE = 512;- // One clock for every document: a stamp only has to order the uses of queries within one cache.- static u64 s_selector_query_use_clock = 0;auto mark_used = [](RefPtr<SelectorQuery const> const& query) {if (query)- query->set_last_use(++s_selector_query_use_clock);+ query->mark_used();};if (m_last_selector_query_text.has_value() && selector_text == *m_last_selector_query_text) {@@ -12497,19 +12495,23 @@ RefPtr<SelectorQuery const> Document::selector_query_for(Utf16View selector_textRefPtr<SelectorQuery const> query;if (maybe_selectors.has_value())query = SelectorQuery::create(maybe_selectors.release_value());- mark_used(query);- // Evict the query used least recently. A page cycling through a working set of selectors that fits the cache then- // stops missing, instead of evicting members of that set over and over. A selector that did not parse has no- // query to recompile and goes first.+ // Evict the oldest query not used since the cache last came to it, sending the used ones it passes to the back. A+ // page cycling through a working set of selectors that fits the cache then stops missing, instead of evicting+ // members of that set over and over. A selector that did not parse has no query to recompile and gets no second+ // turn. A query goes around once per use at most, so a miss costs a constant amount of work on average.if (m_selector_query_cache.size() >= MAX_SELECTOR_QUERY_CACHE_SIZE) {- auto victim = m_selector_query_cache.begin();- for (auto it = m_selector_query_cache.begin(); it != m_selector_query_cache.end(); ++it) {- auto last_use = it->value ? it->value->last_use() : 0;- if (last_use < (victim->value ? victim->value->last_use() : 0))- victim = it;+ while (true) {+ auto oldest = m_selector_query_cache.begin();+ if (!oldest->value || !oldest->value->take_used_mark()) {+ m_selector_query_cache.remove(oldest);+ break;+ }+ auto text = oldest->key;+ auto used_query = oldest->value;+ m_selector_query_cache.remove(oldest);+ m_selector_query_cache.set(move(text), move(used_query));}- m_selector_query_cache.remove(victim);}auto selector_text_copy = Utf16String::from_utf16(selector_text);diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex 81d5fd0fb21..cf4f7bc06f9 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -2514,7 +2514,7 @@ private:// Cache of parsed selector queries for querySelectorAll/querySelector/matches/closest.// A null value means the selector string failed to parse.- mutable HashMap<Utf16String, RefPtr<SelectorQuery const>> m_selector_query_cache;+ mutable OrderedHashMap<Utf16String, RefPtr<SelectorQuery const>> m_selector_query_cache;mutable Optional<Utf16String> m_last_selector_query_text;mutable RefPtr<SelectorQuery const> m_last_selector_query;diff --git a/Libraries/LibWeb/DOM/SelectorQuery.h b/Libraries/LibWeb/DOM/SelectorQuery.hindex c82dbc6eaaa..f2f9ac8171c 100644--- a/Libraries/LibWeb/DOM/SelectorQuery.h+++ b/Libraries/LibWeb/DOM/SelectorQuery.h@@ -39,10 +39,10 @@ public:bool is_result_cacheable() const { return m_is_result_cacheable; }bool depends_on_character_data() const { return m_depends_on_character_data; }- // Stamped by the document's selector query cache each time the query is handed out, so that a full cache can- // evict the query used least recently.- u64 last_use() const { return m_last_use; }- void set_last_use(u64 use) const { m_last_use = use; }+ // Marked by the document's selector query cache each time it hands out the query again, so that a full cache can+ // give a query in use another turn as it looks for one to evict.+ void mark_used() const { m_used_mark = true; }+ bool take_used_mark() const { return exchange(m_used_mark, false); }GC::Ptr<Element> query_first(ParentNode&) const;GC::Ref<NodeList> query_all(ParentNode&) const;@@ -58,7 +58,7 @@ private:// The selectors compiled for the DOM matcher, when a query first needs them, for an HTML document or not.mutable CSS::SelectorFFI::DomSelectorProgram* m_program { nullptr };mutable bool m_program_is_for_html_document { false };- mutable u64 m_last_use { 0 };+ mutable bool m_used_mark { false };// Whether the selector is a lone `*`, which every element matches: a query then collects the// subtree's elements without matching any of them.diff --git a/Tests/LibWeb/Text/expected/DOM/selector-query-cache-eviction.txt b/Tests/LibWeb/Text/expected/DOM/selector-query-cache-eviction.txtnew file mode 100644index 00000000000..a463d0110a5--- /dev/null+++ b/Tests/LibWeb/Text/expected/DOM/selector-query-cache-eviction.txt@@ -0,0 +1,3 @@+1 1 1 2 0 0 0+rounds that answered differently: 0+invalid selectors that did not throw: 0diff --git a/Tests/LibWeb/Text/input/DOM/selector-query-cache-eviction.html b/Tests/LibWeb/Text/input/DOM/selector-query-cache-eviction.htmlnew file mode 100644index 00000000000..908e09e0891--- /dev/null+++ b/Tests/LibWeb/Text/input/DOM/selector-query-cache-eviction.html@@ -0,0 +1,43 @@+<!doctype html>+<div id="target" class="target"></div>+<script src="../include.js"></script>+<script>+ test(() => {+ const target = document.getElementById("target");+ // Selectors the cache holds on to while others go through it, some of which never parse.+ const workingSet = [".target", "div.target", "#target", "[id]", ".absent", "div:not(.target)", "span"];+ const invalid = ["..", "div,", "a|b|c", ":not("];+ const answers = () => workingSet.map(selector => document.querySelectorAll(selector).length).join(" ");++ function throwsSyntaxError(selector) {+ try {+ document.querySelector(selector);+ return false;+ } catch (error) {+ return error.name === "SyntaxError";+ }+ }++ const first = answers();+ println(first);++ let changed = 0;+ let notThrown = 0;+ for (let round = 0; round < 8; ++round) {+ // More selectors than the cache keeps, each new, between uses of the working set.+ for (let index = 0; index < 300; ++index) {+ document.querySelector(`.round-${round}-${index}`);+ throwsSyntaxError(`..round-${round}-${index}`);+ }+ changed += answers() !== first ? 1 : 0;+ for (const selector of invalid) {+ if (!throwsSyntaxError(selector)) {+ println(`did not throw: ${selector}`);+ ++notThrown;+ }+ }+ }+ println(`rounds that answered differently: ${changed}`);+ println(`invalid selectors that did not throw: ${notThrown}`);+ });+</script>