From 43f11163e235be6b3e8ce4eaf0dad1477c911eb1 Mon Sep 17 00:00:00 2001 From: Yegor Date: Thu, 4 Jun 2020 10:53:38 -0700 Subject: [PATCH] Minimize child DOM node moves in many-to-many update (flutter/engine#18648) * minimize child DOM node moves in many-to-many update --- .../lib/src/engine/surface/surface.dart | 200 ++++++++++++++---- .../test/engine/semantics/semantics_test.dart | 2 +- .../engine/surface/scene_builder_test.dart | 134 +++++++++++- 3 files changed, 287 insertions(+), 49 deletions(-) diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/surface.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/surface.dart index 963c5b37c0..dce4664e3d 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/surface.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/surface.dart @@ -184,7 +184,27 @@ bool debugAssertSurfaceState( /// compute the fewest amount of mutations necessary to update the browser DOM. abstract class PersistedSurface implements ui.EngineLayer { /// Creates a persisted surface. - PersistedSurface(); + PersistedSurface(PersistedSurface oldLayer) + : _oldLayer = FrameReference( + oldLayer != null && oldLayer.isActive ? oldLayer : null); + + /// The surface that is being updated using this surface. + /// + /// If not null this surface will reuse the old surface's HTML [element]. + /// + /// This value is set to null at the end of the frame. + PersistedSurface get oldLayer => _oldLayer.value; + final FrameReference _oldLayer; + + /// The index of this surface in its parent's [PersistedContainerSurface._children] + /// list. + /// + /// This index is used to detect whether any child nodes moved within a + /// container layer. The index is cached by the child to avoid a linear + /// look-up in the parent's child list. + /// + /// This index is updated by [PersistedContainerSurface.update]. + int _index = -1; /// Controls the algorithm that reuses the DOM resources owned by this /// surface. @@ -584,7 +604,7 @@ abstract class PersistedSurface implements ui.EngineLayer { /// A surface that doesn't have child surfaces. abstract class PersistedLeafSurface extends PersistedSurface { - PersistedLeafSurface(); + PersistedLeafSurface() : super(null); @override void visitChildren(PersistedSurfaceVisitor visitor) { @@ -598,20 +618,10 @@ abstract class PersistedContainerSurface extends PersistedSurface { /// /// `oldLayer` points to the surface rendered in the previous frame that's /// being updated by this layer. - PersistedContainerSurface(PersistedSurface oldLayer) - : _oldLayer = FrameReference( - oldLayer != null && oldLayer.isActive ? oldLayer : null) { + PersistedContainerSurface(PersistedSurface oldLayer) : super(oldLayer) { assert(oldLayer == null || runtimeType == oldLayer.runtimeType); } - /// The surface that is being updated using this surface. - /// - /// If not null this surface will reuse the old surface's HTML [element]. - /// - /// This value is set to null at the end of the frame. - PersistedSurface get oldLayer => _oldLayer.value; - final FrameReference _oldLayer; - final List _children = []; @override @@ -671,7 +681,9 @@ abstract class PersistedContainerSurface extends PersistedSurface { child.build(); } containerElement.append(child.rootElement); + child._index = i; } + _debugValidateContainerNewState(); } @override @@ -729,8 +741,16 @@ abstract class PersistedContainerSurface extends PersistedSurface { assert(oldChild.childContainer == null); } } + _debugValidateContainerNewState(); + return true; + }()); + } + + void _debugValidateContainerNewState() { + assert(() { for (int i = 0; i < _children.length; i++) { final PersistedSurface newChild = _children[i]; + assert(newChild._index == i); assert(debugAssertSurfaceState(newChild, PersistedSurfaceState.active, PersistedSurfaceState.pendingRetention)); assert(newChild.rootElement != null); @@ -770,6 +790,7 @@ abstract class PersistedContainerSurface extends PersistedSurface { newChild.build(); assert(debugAssertSurfaceState(newChild, PersistedSurfaceState.active)); } + newChild._index = i; assert(newChild.rootElement != null); containerElement.append(newChild.rootElement); } @@ -794,6 +815,7 @@ abstract class PersistedContainerSurface extends PersistedSurface { void _updateManyToOne(PersistedContainerSurface oldSurface) { assert(_children.length == 1); final PersistedSurface newChild = _children[0]; + newChild._index = 0; // Retained child is moved to the correct location in the tree; all others // are released. @@ -886,45 +908,43 @@ abstract class PersistedContainerSurface extends PersistedSurface { // Memoize container element for efficiency. [childContainer] is polymorphic final html.Element containerElement = childContainer; - - PersistedSurface nextSibling; - - // Inserts the DOM node of the child before the DOM node of the next sibling - // if it has moved as a result of the update. Does nothing if the new child - // is already in the right location in the DOM tree. - void insertDomNodeIfMoved(PersistedSurface newChild) { - assert(newChild.rootElement != null); - assert(newChild.parent == this); - final bool reparented = newChild.rootElement.parent != containerElement; - // Do not check for sibling if reparented. It's obvious that we moved. - final bool moved = reparented || - newChild.rootElement.nextElementSibling != nextSibling?.rootElement; - if (moved) { - if (nextSibling == null) { - // We're at the end of the list. - containerElement.append(newChild.rootElement); - } else { - // We're in the middle of the list. - containerElement.insertBefore( - newChild.rootElement, nextSibling.rootElement); - } - } - } - final Map matches = _matchChildren(oldSurface); - for (int bottomInNew = _children.length - 1; - bottomInNew >= 0; - bottomInNew--) { - final PersistedSurface newChild = _children[bottomInNew]; + // This pair of lists maps from _children indices to oldSurface._children indices. + // These lists are initialized lazily, only when we discover that we will need to + // move nodes around. Otherwise, these lists remain null. + List indexMapNew; + List indexMapOld; + + // Whether children need to move around the DOM. It is common for children + // to be updated/retained but never move. Knowing this allows us to bypass + // the expensive logic that figures out the minimal number of moves. + bool requiresDomInserts = false; + + for (int topInNew = 0; topInNew < _children.length; topInNew += 1) { + final PersistedSurface newChild = _children[topInNew]; + + // The old child surface that `newChild` was updated or retained from. + PersistedSurface matchedOldChild; + // Whether the child is getting a new parent. This happens in the + // following situations: + // - It's a new child and is being attached for the first time. + // - It's an existing child is being updated or retained and at the same + // time moved to another parent. + bool isReparenting = true; + if (newChild.isPendingRetention) { + isReparenting = newChild.rootElement.parent != containerElement; newChild.retain(); + matchedOldChild = newChild; assert(debugAssertSurfaceState( newChild, PersistedSurfaceState.pendingRetention)); } else if (newChild is PersistedContainerSurface && newChild.oldLayer != null) { final PersistedContainerSurface oldLayer = newChild.oldLayer; + isReparenting = oldLayer.rootElement.parent != containerElement; + matchedOldChild = oldLayer; assert(debugAssertSurfaceState( oldLayer, PersistedSurfaceState.pendingUpdate)); newChild.update(oldLayer); @@ -932,10 +952,11 @@ abstract class PersistedContainerSurface extends PersistedSurface { debugAssertSurfaceState(oldLayer, PersistedSurfaceState.released)); assert(debugAssertSurfaceState(newChild, PersistedSurfaceState.active)); } else { - final PersistedSurface matchedOldChild = matches[newChild]; + matchedOldChild = matches[newChild]; if (matchedOldChild != null) { assert(debugAssertSurfaceState( matchedOldChild, PersistedSurfaceState.active)); + isReparenting = matchedOldChild.rootElement.parent != containerElement; newChild.update(matchedOldChild); assert(debugAssertSurfaceState( matchedOldChild, PersistedSurfaceState.released)); @@ -947,17 +968,89 @@ abstract class PersistedContainerSurface extends PersistedSurface { debugAssertSurfaceState(newChild, PersistedSurfaceState.active)); } } - insertDomNodeIfMoved(newChild); + + int indexInOld = -1; + if (matchedOldChild != null && !isReparenting) { + assert( + matchedOldChild._index != -1, + 'Invalid index ${matchedOldChild._index} of child layer ${matchedOldChild.runtimeType}', + ); + indexInOld = matchedOldChild._index; + } + + // indexInOld != topInNew indicates that at least one child has moved and + // therefore we'll need to find the minimum moves necessary to update the + // child list. + if (!requiresDomInserts && indexInOld != topInNew) { + requiresDomInserts = true; + indexMapNew = []; + indexMapOld = []; + + // Because up until this moment we haven't been populating the + // indexMapNew and indexMapOld, we backfill them with indices up until + // the current index. + for (int backfill = 0; backfill < topInNew; backfill++) { + indexMapNew.add(backfill); + indexMapOld.add(backfill); + } + } + if (requiresDomInserts && indexInOld != -1) { + indexMapNew.add(topInNew); + indexMapOld.add(indexInOld); + } + + newChild._index = topInNew; assert(newChild.rootElement != null); assert(debugAssertSurfaceState(newChild, PersistedSurfaceState.active, PersistedSurfaceState.pendingRetention)); - nextSibling = newChild; + } + + // Avoid calling `_insertChildDomNodes` unnecessarily. Only call it if we + // actually need to move DOM nodes around. + if (requiresDomInserts) { + assert(indexMapNew.length == indexMapOld.length); + _insertChildDomNodes(indexMapNew, indexMapOld); + } else { + // The fast path, where nothing needs to move, should not intialize the + // mapping lists at all. + assert(indexMapNew == null); + assert(indexMapOld == null); } // Remove elements that were not reused this frame. _discardActiveChildren(oldSurface); } + /// Performs the minimum number of DOM moves necessary to put all children in + /// the right place in the DOM. + void _insertChildDomNodes(List indexMapNew, List indexMapOld) { + final List stationaryIndices = longestIncreasingSubsequence(indexMapOld); + + // Convert to stationary new indices + for (int i = 0; i < stationaryIndices.length; i++) { + stationaryIndices[i] = indexMapNew[stationaryIndices[i]]; + } + + html.HtmlElement refNode; + final html.Element containerElement = childContainer; + for (int i = _children.length - 1; i >= 0; i -= 1) { + final int indexInNew = indexMapNew.indexOf(i); + final bool isStationary = indexInNew != -1 && stationaryIndices.contains(i); + final PersistedSurface child = _children[i]; + final html.HtmlElement childElement = child.rootElement; + assert(childElement != null); + if (!isStationary) { + if (refNode == null) { + containerElement.append(childElement); + } else { + containerElement.insertBefore(childElement, refNode); + } + } + refNode = childElement; + assert(child.rootElement.parent == childContainer); + } + } + Map _matchChildren( PersistedContainerSurface oldSurface) { final int newUnfilteredChildCount = _children.length; @@ -967,7 +1060,9 @@ abstract class PersistedContainerSurface extends PersistedSurface { final List newChildren = []; for (int i = 0; i < newUnfilteredChildCount; i++) { final PersistedSurface child = _children[i]; - if (child.isCreated) { + // If child has an old layer, it means it's scheduled for an explicit + // update, and therefore there's no need to try to match it. + if (child.isCreated && child.oldLayer == null) { newChildren.add(child); } } @@ -1023,7 +1118,9 @@ abstract class PersistedContainerSurface extends PersistedSurface { final _PersistedSurfaceMatch match = allMatches[i]; // This may be null if it has been claimed. final PersistedSurface matchedChild = oldChildren[match.oldChildIndex]; - if (matchedChild != null) { + // Whether the new child hasn't found a match yet. + final bool newChildNeedsMatch = result[match.newChild] == null; + if (matchedChild != null && newChildNeedsMatch) { oldChildren[match.oldChildIndex] = null; result[match.newChild] = matchedChild; // claim it } @@ -1105,4 +1202,13 @@ class _PersistedSurfaceMatch { /// The score of how well [newChild] matched the old child as computed by /// [PersistedSurface.matchForUpdate]. final double matchQuality; + + @override + String toString() { + if (assertionsEnabled) { + return '_PersistedSurfaceMatch(${newChild.runtimeType}#${newChild.hashCode}: $oldChildIndex, quality: $matchQuality)'; + } else { + return super.toString(); + } + } } diff --git a/engine/src/flutter/lib/web_ui/test/engine/semantics/semantics_test.dart b/engine/src/flutter/lib/web_ui/test/engine/semantics/semantics_test.dart index 7d09b04c6a..66a337cce2 100644 --- a/engine/src/flutter/lib/web_ui/test/engine/semantics/semantics_test.dart +++ b/engine/src/flutter/lib/web_ui/test/engine/semantics/semantics_test.dart @@ -3,7 +3,7 @@ // found in the LICENSE file. // @dart = 2.6 -@TestOn('vm && linux') +@TestOn('chrome') // TODO(nurhan): https://github.com/flutter/flutter/issues/50590 import 'dart:async'; diff --git a/engine/src/flutter/lib/web_ui/test/engine/surface/scene_builder_test.dart b/engine/src/flutter/lib/web_ui/test/engine/surface/scene_builder_test.dart index 349681c5fd..d323733649 100644 --- a/engine/src/flutter/lib/web_ui/test/engine/surface/scene_builder_test.dart +++ b/engine/src/flutter/lib/web_ui/test/engine/surface/scene_builder_test.dart @@ -3,16 +3,21 @@ // found in the LICENSE file. // @dart = 2.6 +import 'dart:async'; import 'dart:html' as html; import 'dart:js_util' as js_util; import 'package:ui/src/engine.dart'; -import 'package:ui/ui.dart'; +import 'package:ui/ui.dart' hide window; import 'package:test/test.dart'; import '../../matchers.dart'; void main() { + setUpAll(() async { + await webOnlyInitializeEngine(); + }); + group('SceneBuilder', () { test('pushOffset implements surface lifecycle', () { testLayerLifeCycle((SceneBuilder sceneBuilder, EngineLayer oldLayer) { @@ -343,6 +348,133 @@ void main() { html.HtmlElement content = builder.build().webOnlyRootElement; expect(content.querySelectorAll('flt-offset'), hasLength(5)); }); + + test('updates child lists efficiently', () async { + // Pushes a single child that renders one character. + // + // If the character is a number, pushes an offset layer. Otherwise, pushes + // an offset layer. Test cases use this to control how layers are reused. + // Layers of the same type can be reused even if they are not explicitly + // updated. Conversely, layers of different types are never reused. + EngineLayer pushChild(SurfaceSceneBuilder builder, String char, {EngineLayer oldLayer}) { + // Numbers use opacity layers, letters use offset layers. This is used to + // control DOM reuse. Layers of the same type can reuse DOM nodes from other + // dropped layers. + final bool useOffset = int.tryParse(char) == null; + final EnginePictureRecorder recorder = PictureRecorder(); + final RecordingCanvas canvas = recorder.beginRecording(const Rect.fromLTRB(0, 0, 400, 400)); + final Paragraph paragraph = (ParagraphBuilder(ParagraphStyle())..addText(char)).build(); + paragraph.layout(ParagraphConstraints(width: 1000)); + canvas.drawParagraph(paragraph, Offset.zero); + final EngineLayer newLayer = useOffset + ? builder.pushOffset(0, 0, oldLayer: oldLayer) + : builder.pushOpacity(100, oldLayer: oldLayer); + builder.addPicture(Offset.zero, recorder.endRecording()); + builder.pop(); + return newLayer; + } + + // Maps letters to layers used to render them in the last frame, used to + // supply `oldLayer` to guarantee update. + final Map renderedLayers = {}; + + // Pump an empty scene to reset it, otherwise the first frame will attempt + // to diff left-overs from a previous test, which results in unpredictable + // DOM mutations. + window.render(SurfaceSceneBuilder().build()); + + // Renders a `string` by breaking it up into individual characters and + // rendering each character into its own layer. + Future testCase(String string, String description, { int deletions = 0, int additions = 0, int moves = 0 }) { + print('Testing "$string" - $description'); + final Set actualDeletions = {}; + final Set actualAdditions = {}; + + // Watches DOM mutations and counts deletions and additions to the child + // list of the `` element. + final html.MutationObserver observer = html.MutationObserver((List mutations, _) { + for (html.MutationRecord record in mutations.cast()) { + actualDeletions.addAll(record.removedNodes); + actualAdditions.addAll(record.addedNodes); + } + }); + observer.observe(SurfaceSceneBuilder.debugLastFrameScene.rootElement, childList: true); + + final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); + for (int i = 0; i < string.length; i++) { + final String char = string[i]; + renderedLayers[char] = pushChild(builder, char, oldLayer: renderedLayers[char]); + } + final SurfaceScene scene = builder.build(); + final List pTags = scene.webOnlyRootElement.querySelectorAll('p'); + expect(pTags, hasLength(string.length)); + expect( + scene.webOnlyRootElement.querySelectorAll('p').map((p) => p.innerText).join(''), + string, + ); + renderedLayers.removeWhere((key, value) => !string.contains(key)); + + // Inject a zero-duration timer to allow mutation observers to receive notification. + return Future.delayed(Duration.zero).then((_) { + observer.disconnect(); + + // Nodes that are removed then added are classified as "moves". + final int actualMoves = actualAdditions.intersection(actualDeletions).length; + // Compare all at once instead of one by one because when it fails, it's + // much more useful to see all numbers, not just the one that failed to + // match. + expect( + { + 'additions': actualAdditions.length - actualMoves, + 'deletions': actualDeletions.length - actualMoves, + 'moves': actualMoves, + }, + { + 'additions': additions, + 'deletions': deletions, + 'moves': moves, + }, + ); + }); + } + + // Adding + await testCase('', 'noop'); + await testCase('', 'noop'); + await testCase('be', 'zero-to-many', additions: 2); + await testCase('bcde', 'insert in the middle', additions: 2); + await testCase('abcde', 'prepend', additions: 1); + await testCase('abcdef', 'append', additions: 1); + + // Moving + await testCase('fbcdea', 'swap at ends', moves: 2); + await testCase('fecdba', 'swap in the middle', moves: 2); + await testCase('fedcba', 'swap adjacent in one move', moves: 1); + await testCase('fedcba', 'non-empty noop'); + await testCase('afedcb', 'shift right by 1', moves: 1); + await testCase('fedcba', 'shift left by 1', moves: 1); + await testCase('abcdef', 'reverse', moves: 5); + await testCase('efabcd', 'shift right by 2', moves: 2); + await testCase('abcdef', 'shift left by 2', moves: 2); + + // Scrolling without DOM reuse (numbers and letters use different types of layers) + await testCase('9abcde', 'scroll right by 1', additions: 1, deletions: 1); + await testCase('789abc', 'scroll right by 2', additions: 2, deletions: 2); + await testCase('89abcd', 'scroll left by 1', additions: 1, deletions: 1); + await testCase('abcdef', 'scroll left by 2', additions: 2, deletions: 2); + + // Scrolling with DOM reuse + await testCase('zabcde', 'scroll right by 1', moves: 1); + await testCase('xyzabc', 'scroll right by 2', moves: 2); + await testCase('yzabcd', 'scroll left by 1', moves: 1); + await testCase('abcdef', 'scroll left by 2', moves: 2); + + // Removing + await testCase('bcdef', 'remove as start', deletions: 1); + await testCase('bcde', 'remove as end', deletions: 1); + await testCase('be', 'remove in the middle', deletions: 2); + await testCase('', 'remove all', deletions: 2); + }); } typedef TestLayerBuilder = EngineLayer Function(