Browse Source

perf: optimize data structures in context_bridge::ObjectCache (#27639)

* Use std::forward_list instead of base::LinkedList for better perf,
more consistent memory management.  Better than std::list because we
don't need the double-linked-list behavior of std::list
* Use std::unordered_map instead of std::map for the v8 hash table
Samuel Attard 4 years ago
parent
commit
09870d97b5

+ 3 - 19
shell/renderer/api/context_bridge/object_cache.cc

@@ -14,22 +14,8 @@ namespace api {
 
 namespace context_bridge {
 
-ObjectCachePairNode::ObjectCachePairNode(ObjectCachePair&& pair) {
-  this->pair = std::move(pair);
-}
-
-ObjectCachePairNode::~ObjectCachePairNode() = default;
-
 ObjectCache::ObjectCache() {}
-ObjectCache::~ObjectCache() {
-  for (const auto& pair : proxy_map_) {
-    while (!pair.second.empty()) {
-      ObjectCachePairNode* node = pair.second.head()->value();
-      node->RemoveFromList();
-      delete node;
-    }
-  }
-}
+ObjectCache::~ObjectCache() = default;
 
 void ObjectCache::CacheProxiedObject(v8::Local<v8::Value> from,
                                      v8::Local<v8::Value> proxy_value) {
@@ -37,8 +23,7 @@ void ObjectCache::CacheProxiedObject(v8::Local<v8::Value> from,
     auto obj = v8::Local<v8::Object>::Cast(from);
     int hash = obj->GetIdentityHash();
 
-    auto* node = new ObjectCachePairNode(std::make_pair(from, proxy_value));
-    proxy_map_[hash].Append(node);
+    proxy_map_[hash].push_front(std::make_pair(from, proxy_value));
   }
 }
 
@@ -54,8 +39,7 @@ v8::MaybeLocal<v8::Value> ObjectCache::GetCachedProxiedObject(
     return v8::MaybeLocal<v8::Value>();
 
   auto& list = iter->second;
-  for (auto* node = list.head(); node != list.end(); node = node->next()) {
-    auto& pair = node->value()->pair;
+  for (const auto& pair : list) {
     auto from_cmp = pair.first;
     if (from_cmp == from) {
       if (pair.second.IsEmpty())

+ 2 - 9
shell/renderer/api/context_bridge/object_cache.h

@@ -5,7 +5,7 @@
 #ifndef SHELL_RENDERER_API_CONTEXT_BRIDGE_OBJECT_CACHE_H_
 #define SHELL_RENDERER_API_CONTEXT_BRIDGE_OBJECT_CACHE_H_
 
-#include <map>
+#include <unordered_map>
 #include <utility>
 
 #include "base/containers/linked_list.h"
@@ -22,13 +22,6 @@ namespace context_bridge {
 
 using ObjectCachePair = std::pair<v8::Local<v8::Value>, v8::Local<v8::Value>>;
 
-struct ObjectCachePairNode : public base::LinkNode<ObjectCachePairNode> {
-  explicit ObjectCachePairNode(ObjectCachePair&& pair);
-  ~ObjectCachePairNode();
-
-  ObjectCachePair pair;
-};
-
 class ObjectCache final {
  public:
   ObjectCache();
@@ -41,7 +34,7 @@ class ObjectCache final {
 
  private:
   // object_identity ==> [from_value, proxy_value]
-  std::map<int, base::LinkedList<ObjectCachePairNode>> proxy_map_;
+  std::unordered_map<int, std::forward_list<ObjectCachePair>> proxy_map_;
 };
 
 }  // namespace context_bridge