Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 34 additions & 15 deletions packages/flame/lib/src/components/core/component.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1117,26 +1117,45 @@ class Component {
_removeCompleter = null;
}

/// Reusable buffer for [_remove]. A fresh list is used in the rare case of
/// a re-entrant teardown (e.g. a nested game disposed from `onRemove`).
static final List<Component> _teardownBuffer = [];

void _remove(Component parent) {
parent._internalChildren.remove(this);
propagateToChildren(
(Component component) {
component
..onRemove()
.._unregisterKey()
.._clearMountedBit()
.._clearRemovingBit()
.._setRemovedBit()
.._removeCompleter?.complete()
.._removeCompleter = null
.._parent!.onChildrenChanged(component, ChildrenChangeType.removed);
return true;
},
includeSelf: true,
);
final buffer = _teardownBuffer.isEmpty ? _teardownBuffer : <Component>[];

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is allocating one empty list per component removal that significant? feels like this static cache is introducing potential future concurrency problems or hard to find headaches. seems that major gain here is the non-generator teardown and not the brittle [] cache?

_collectTeardown(buffer);
for (var i = 0; i < buffer.length; i++) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please don't say that dart's built-in for each has some hidden performance cost too 😵‍💫

final component = buffer[i];
component
..onRemove()
.._unregisterKey()
.._clearMountedBit()
.._clearRemovingBit()
.._setRemovedBit()
.._removeCompleter?.complete()
.._removeCompleter = null
.._parent!.onChildrenChanged(component, ChildrenChangeType.removed);
}
buffer.clear();
_parent = null;
}

/// Collects this component and all its descendants into [out] in teardown
/// order: leaves first, siblings in reverse order, ancestors after their
/// subtrees. This matches the order that
/// `descendants(reversed: true, includeSelf: true)` would produce, without
/// allocating generator frames on every removal.
void _collectTeardown(List<Component> out) {
final children = _children;
if (children != null) {
for (final child in children.reversed()) {
child._collectTeardown(out);
}
}
out.add(this);
}

void _unregisterKey() {
if (key != null) {
final game = findGame();
Expand Down
Loading