Skip to content

Commit 046fc1b

Browse files
committed
perf: optimize accumulation statistics calculation
Refactor the accumulation statistics logic to use pre-calculated dictionaries for digest counts and gas usage, eliminating repeated filtering inside the loop.
1 parent 0f904ac commit 046fc1b

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

Blockchain/Sources/Blockchain/RuntimeProtocols/Accumulation.swift

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -662,13 +662,19 @@ extension Accumulation {
662662
// get accumulation statistics
663663
var accumulateStats = AccumulationStats()
664664
let digests = accumulated.compactMap(\.digests).flatMap(\.self)
665-
for (service, _) in accumulateOutput.gasUsed {
666-
if accumulateStats[service] != nil { continue }
667665

668-
let num = digests.filter { $0.serviceIndex == service }.count
669-
let gasUsed = accumulateOutput.gasUsed
670-
.filter { $0.serviceIndex == service }
671-
.reduce(Gas(0)) { $0 + $1.gas }
666+
var digestCounts: [ServiceIndex: Int] = [:]
667+
for digest in digests {
668+
digestCounts[digest.serviceIndex, default: 0] += 1
669+
}
670+
671+
var gasUsedMap: [ServiceIndex: Gas] = [:]
672+
for (service, gas) in accumulateOutput.gasUsed {
673+
gasUsedMap[service, default: Gas(0)] += gas
674+
}
675+
676+
for (service, gasUsed) in gasUsedMap {
677+
let num = digestCounts[service] ?? 0
672678
if Int(gasUsed.value) + num == 0 { continue }
673679

674680
accumulateStats[service] = (gasUsed, UInt32(num))

0 commit comments

Comments
 (0)