From 5dca3e7c7411ca370e0d9911fdef9f3a88dc14b4 Mon Sep 17 00:00:00 2001 From: Valentin Shergin Date: Tue, 10 Apr 2018 12:45:51 -0700 Subject: [PATCH] Fabric: New approach of mutating ShadowNode's children collection Summary: Previously we recreate a vector with pointers to child nodes every single time we modify the collection. That was okay but recently I realized that the we can simply make a copy of the vector one time during object construction and then mutate it freely. Reviewed By: mdvacca Differential Revision: D7467796 fbshipit-source-id: 660f1706a19ae5f07c34c509f411ce9d67b93b35 --- .../fabric/core/shadownode/ShadowNode.cpp | 20 ++++++------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/ReactCommon/fabric/core/shadownode/ShadowNode.cpp b/ReactCommon/fabric/core/shadownode/ShadowNode.cpp index c2da0db17ee..f15964b0b5d 100644 --- a/ReactCommon/fabric/core/shadownode/ShadowNode.cpp +++ b/ReactCommon/fabric/core/shadownode/ShadowNode.cpp @@ -31,7 +31,7 @@ ShadowNode::ShadowNode( rootTag_(rootTag), instanceHandle_(instanceHandle), props_(props), - children_(children), + children_(std::make_shared(*children)), revision_(1) {} ShadowNode::ShadowNode( @@ -43,7 +43,7 @@ ShadowNode::ShadowNode( rootTag_(shadowNode->rootTag_), instanceHandle_(shadowNode->instanceHandle_), props_(props ? props : shadowNode->props_), - children_(children ? children : shadowNode->children_), + children_(std::make_shared(*(children ? children : shadowNode->children_))), sourceNode_(shadowNode), revision_(shadowNode->revision_ + 1) {} @@ -92,23 +92,15 @@ void ShadowNode::sealRecursive() const { void ShadowNode::appendChild(const SharedShadowNode &child) { ensureUnsealed(); - // We cannot mutate `children_` in place here because it is a *shared* - // data structure which means other `ShadowNodes` might refer to its old value. - // So, we have to clone this and only then mutate. - auto nonConstChildrenCopy = SharedShadowNodeList(*children_); - nonConstChildrenCopy.push_back(child); - children_ = std::make_shared(nonConstChildrenCopy); + auto nonConstChildren = std::const_pointer_cast(children_); + nonConstChildren->push_back(child); } void ShadowNode::replaceChild(const SharedShadowNode &oldChild, const SharedShadowNode &newChild) { ensureUnsealed(); - // We cannot mutate `children_` in place here because it is a *shared* - // data structure which means other `ShadowNodes` might refer to its old value. - // So, we have to clone this and only then mutate. - auto nonConstChildrenCopy = SharedShadowNodeList(*children_); - std::replace(nonConstChildrenCopy.begin(), nonConstChildrenCopy.end(), oldChild, newChild); - children_ = std::make_shared(nonConstChildrenCopy); + auto nonConstChildren = std::const_pointer_cast(children_); + std::replace(nonConstChildren->begin(), nonConstChildren->end(), oldChild, newChild); } void ShadowNode::clearSourceNode() {