mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2025-07-30 04:39:06 +00:00
LibWeb: Maintain a mapping for fast lookup in getElementById()
With this change we maintain a data structure that maps ids to corresponding elements. This allows us to avoid tree traversal in getElementById() in all cases except ones when lookup happens for unconnected elements.
This commit is contained in:
parent
7165d69868
commit
8cae20af1b
Notes:
github-actions[bot]
2025-03-26 08:37:18 +00:00
Author: https://github.com/kalenikaliaksandr
Commit: 8cae20af1b
Pull-request: https://github.com/LadybirdBrowser/ladybird/pull/4086
15 changed files with 157 additions and 51 deletions
39
Libraries/LibWeb/DOM/ElementByIdMap.cpp
Normal file
39
Libraries/LibWeb/DOM/ElementByIdMap.cpp
Normal file
|
@ -0,0 +1,39 @@
|
|||
/*
|
||||
* Copyright (c) 2025, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#include <LibWeb/DOM/ElementByIdMap.h>
|
||||
|
||||
namespace Web::DOM {
|
||||
|
||||
void ElementByIdMap::add(FlyString const& element_id, Element& element)
|
||||
{
|
||||
auto& elements_with_id = m_map.ensure(element_id, [] { return Vector<WeakPtr<Element>> {}; });
|
||||
|
||||
// Remove all elements that were deallocated.
|
||||
elements_with_id.remove_all_matching([](WeakPtr<Element>& element) {
|
||||
return !element.has_value();
|
||||
});
|
||||
|
||||
VERIFY(!elements_with_id.contains_slow(element));
|
||||
elements_with_id.insert_before_matching(element, [&](auto& another_element) {
|
||||
return element.is_before(*another_element);
|
||||
});
|
||||
}
|
||||
|
||||
void ElementByIdMap::remove(FlyString const& element_id, Element& element)
|
||||
{
|
||||
auto maybe_elements_with_id = m_map.get(element_id);
|
||||
if (!maybe_elements_with_id.has_value())
|
||||
return;
|
||||
auto& elements_with_id = *maybe_elements_with_id;
|
||||
elements_with_id.remove_all_matching([&](auto& another_element) {
|
||||
if (!another_element.has_value())
|
||||
return true;
|
||||
return &element == another_element.ptr();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue