From a3b9c33d261b22c7698e50efffa9022d9e2e11cd Mon Sep 17 00:00:00 2001 From: rikbellens Date: Wed, 28 Feb 2024 13:39:28 +0100 Subject: [PATCH] perf: improve speed of TreeSetView.elementAt --- lib/src/treeset.dart | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/lib/src/treeset.dart b/lib/src/treeset.dart index af14b8e..3a9b0cd 100644 --- a/lib/src/treeset.dart +++ b/lib/src/treeset.dart @@ -916,20 +916,32 @@ class _Path { } factory _Path.minimum(AvlNode node, [_Path? parent]) { - if (node.left == null) return _Path(node, parent); - return _Path.minimum(node.left!, _Path(node, parent)); + var p = _Path(node, parent); + while (p.node.left != null) { + p = _Path(p.node.left!, p); + } + return p; } factory _Path.maximum(AvlNode node, [_Path? parent]) { - if (node.right == null) return _Path(node, parent); - return _Path.maximum(node.right!, _Path(node, parent)); + var p = _Path(node, parent); + while (p.node.right != null) { + p = _Path(p.node.right!, p); + } + return p; } - int get leftIndex => - (parent?.leftIndex ?? 0) + - (node == parent?.node.right ? ((parent!.node.left?.length ?? 0) + 1) : 0); - - int get index => leftIndex + (node.left?.length ?? 0); + int get index { + var v = node.left?.length ?? 0; + var p = this; + while (p.parent != null) { + if (p.node == p.parent!.node.right) { + v += (p.parent!.node.left?.length ?? 0) + 1; + } + p = p.parent!; + } + return v; + } _Path? next() { var current = node;