From 4aa9cc17fc91feb60d406bd273206ddb7d43f431 Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Thu, 10 Sep 2026 09:25:15 +0800 Subject: [PATCH] chore: avoid redundant select calculations in DomainSet Once the key is exhausted, a terminal node completes the match; otherwise only saved wildcard branches can still succeed. No input remains to match the current node's child edges, so their starting position is unnecessary. Defer the child-edge select in Has until more input needs matching, both after matching a byte and when restoring a wildcard. Keep the node-terminator select needed to resume saved wildcard branches. Earlier candidate benchmarks show median query times ~3%/~1% lower for short/long queries and ~11%/~8% lower for exact/mixed-rule workloads, with no additional allocations or changes to the index layout. --- component/trie/domain_set.go | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/component/trie/domain_set.go b/component/trie/domain_set.go index 1d8ec3759..574237599 100644 --- a/component/trie/domain_set.go +++ b/component/trie/domain_set.go @@ -162,16 +162,20 @@ func (ss *DomainSet) Has(key string) bool { stack = stack[0 : len(stack)-1] // back wildcard and find next node nextNodeId := countZeros(ss.labelBitmap, ss.ranks, cursor.bmIdx+1) - nextBmIdx := selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nextNodeId-1) + 1 j := cursor.index for ; j < len(key) && revLowerAt(key, j) != domainStepByte; j++ { } if j == len(key) { if getBit(ss.leaves, nextNodeId) != 0 { + // The wildcard consumed the rest of the key and reached a + // terminal node, so this branch matches. return true } + // Otherwise, this node is not terminal and this wildcard branch + // has no input left for child edges. Try any remaining saved wildcards. continue } + nextBmIdx := selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nextNodeId-1) + 1 for ; getBit(ss.labelBitmap, nextBmIdx) == 0; nextBmIdx++ { if ss.labels[nextBmIdx-nextNodeId] == domainStepByte { bmIdx = nextBmIdx @@ -196,11 +200,20 @@ func (ss *DomainSet) Has(key string) bool { } } nodeId = bmIdx - nodeId + 1 // countZeros(ss.labelBitmap, ss.ranks, bmIdx+1) - bmIdx = selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nodeId-1) + 1 - if i == len(key)-1 && getBit(ss.leaves, nodeId) == 0 && len(stack) > 0 { + if i == len(key)-1 { + if getBit(ss.leaves, nodeId) != 0 { + // All input is consumed at a terminal node, so the key matches. + return true + } + if len(stack) == 0 { + // No input remains for this non-terminal node's child edges. + // With no saved wildcard branches left, the key cannot match. + return false + } bmIdx = selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nodeId) goto RESTART } + bmIdx = selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nodeId-1) + 1 } return getBit(ss.leaves, nodeId) != 0