From ae498fc74ab5d9be3761d3500a4af2e300187253 Mon Sep 17 00:00:00 2001 From: lisonge Date: Mon, 6 Nov 2023 20:38:14 +0800 Subject: [PATCH] perf: getDescendants --- .../main/java/li/songe/gkd/service/AbExt.kt | 2 +- .../kotlin/li/songe/selector/Transform.kt | 18 +++++++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/li/songe/gkd/service/AbExt.kt b/app/src/main/java/li/songe/gkd/service/AbExt.kt index d21c813d3..b71c3c11d 100644 --- a/app/src/main/java/li/songe/gkd/service/AbExt.kt +++ b/app/src/main/java/li/songe/gkd/service/AbExt.kt @@ -148,7 +148,7 @@ val abTransform = Transform( getParent = { node -> node.parent }, getDescendants = { node -> sequence { - val stack = mutableListOf(node) + val stack = getChildren(node).toMutableList() val tempNodes = mutableListOf() do { val top = stack.removeLast() diff --git a/selector/src/commonMain/kotlin/li/songe/selector/Transform.kt b/selector/src/commonMain/kotlin/li/songe/selector/Transform.kt index 3c2a32970..395d304f8 100644 --- a/selector/src/commonMain/kotlin/li/songe/selector/Transform.kt +++ b/selector/src/commonMain/kotlin/li/songe/selector/Transform.kt @@ -46,15 +46,20 @@ class Transform( ) }, + /** + * 遍历下面所有子孙节点,不包含自己 + */ val getDescendants: (T) -> Sequence = { node -> sequence { // 深度优先 先序遍历 // https://developer.mozilla.org/zh-CN/docs/Web/API/Document/querySelector - val stack = mutableListOf(node) + val stack = getChildren(node).toMutableList() + stack.reverse() val tempNodes = mutableListOf() do { val top = stack.removeLast() yield(top) for (childNode in getChildren(top)) { + // 可针对 sequence 优化 tempNodes.add(childNode) } if (tempNodes.isNotEmpty()) { @@ -71,10 +76,13 @@ class Transform( val querySelectorAll: (T, Selector) -> Sequence = { node, selector -> sequence { + // cache trackNodes val trackNodes: MutableList = mutableListOf() + val r0 = selector.match(node, this@Transform, trackNodes) + if (r0 != null) yield(r0) getDescendants(node).forEach { childNode -> - val r = selector.match(childNode, this@Transform, trackNodes) trackNodes.clear() + val r = selector.match(childNode, this@Transform, trackNodes) if (r != null) yield(r) } } @@ -86,10 +94,10 @@ class Transform( } val querySelectorTrackAll: (T, Selector) -> Sequence> = { node, selector -> sequence { - val trackNodes: MutableList = mutableListOf() + val r0 = selector.matchTracks(node, this@Transform) + if (r0 != null) yield(r0) getDescendants(node).forEach { childNode -> - val r = selector.matchTracks(childNode, this@Transform, trackNodes)?.toList() - trackNodes.clear() + val r = selector.matchTracks(childNode, this@Transform) if (r != null) yield(r) } }