From 1be9fab5bf20e75d61456d8c85be3607f0227ad3 Mon Sep 17 00:00:00 2001 From: YK Date: Sat, 17 Jan 2026 01:33:48 +0800 Subject: [PATCH] perf: Optimize multiproof sequencer `add_proof` (#21129) --- .../src/tree/payload_processor/multiproof.rs | 31 +++++++++++-------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/crates/engine/tree/src/tree/payload_processor/multiproof.rs b/crates/engine/tree/src/tree/payload_processor/multiproof.rs index d3907720b5..b5f1272b67 100644 --- a/crates/engine/tree/src/tree/payload_processor/multiproof.rs +++ b/crates/engine/tree/src/tree/payload_processor/multiproof.rs @@ -141,22 +141,27 @@ impl ProofSequencer { /// Adds a proof with the corresponding state update and returns all sequential proofs and state /// updates if we have a continuous sequence fn add_proof(&mut self, sequence: u64, update: SparseTrieUpdate) -> Vec { - if sequence >= self.next_to_deliver { + // Optimization: fast path for in-order delivery to avoid BTreeMap overhead. + // If this is the expected sequence, return it immediately without buffering. + if sequence == self.next_to_deliver { + let mut consecutive_proofs = Vec::with_capacity(1); + consecutive_proofs.push(update); + self.next_to_deliver += 1; + + // Check if we have subsequent proofs in the pending buffer + while let Some(pending) = self.pending_proofs.remove(&self.next_to_deliver) { + consecutive_proofs.push(pending); + self.next_to_deliver += 1; + } + + return consecutive_proofs; + } + + if sequence > self.next_to_deliver { self.pending_proofs.insert(sequence, update); } - let mut consecutive_proofs = Vec::with_capacity(self.pending_proofs.len()); - let mut current_sequence = self.next_to_deliver; - - // keep collecting proofs and state updates as long as we have consecutive sequence numbers - while let Some(pending) = self.pending_proofs.remove(¤t_sequence) { - consecutive_proofs.push(pending); - current_sequence += 1; - } - - self.next_to_deliver += consecutive_proofs.len() as u64; - - consecutive_proofs + Vec::new() } /// Returns true if we still have pending proofs