Skip to content

perf(core): reuse buffer in trie commits (WIP) #3511

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions crates/common/trie/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod leaf;

use std::{
array,
collections::btree_map::Range,
sync::{Arc, OnceLock},
};

Expand Down Expand Up @@ -51,23 +52,30 @@ impl NodeRef {
}
}

pub fn commit(&mut self, acc: &mut Vec<(NodeHash, Vec<u8>)>) -> NodeHash {
pub fn commit(
&mut self,
buffer: &mut Vec<u8>,
acc: &mut Vec<(NodeHash, std::ops::Range<usize>)>,
) -> NodeHash {
match *self {
NodeRef::Node(ref mut node, ref mut hash) => {
match Arc::make_mut(node) {
Node::Branch(node) => {
for node in &mut node.choices {
node.commit(acc);
node.commit(buffer, acc);
}
}
Node::Extension(node) => {
node.child.commit(acc);
node.child.commit(buffer, acc);
}
Node::Leaf(_) => {}
}

let hash = hash.get_or_init(|| node.compute_hash());
acc.push((*hash, node.encode_to_vec()));
let first = buffer.len();
node.encode(buffer);
let last = buffer.len();
acc.push((*hash, (first..last)));

let hash = *hash;
*self = hash.into();
Expand Down
18 changes: 14 additions & 4 deletions crates/common/trie/trie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,13 @@ impl Trie {
pub fn commit(&mut self) -> Result<(), TrieError> {
if self.root.is_valid() {
let mut acc = Vec::new();
self.root.commit(&mut acc);
self.db.put_batch(acc)?; // we'll try to avoid calling this for every commit
let mut buffer = Vec::new();
self.root.commit(&mut buffer, &mut acc);
let updates: Vec<(NodeHash, Vec<u8>)> = acc
.iter()
.map(|(hash, range)| (*hash, buffer[range.clone()].to_vec()))
.collect();
self.db.put_batch(updates)?; // we'll try to avoid calling this for every commit
}

Ok(())
Expand All @@ -187,11 +192,16 @@ impl Trie {
/// Nodes are given with their hash pre-calculated.
pub fn commit_without_storing(&mut self) -> Vec<TrieNode> {
let mut acc = Vec::new();
let mut buffer = Vec::new();
if self.root.is_valid() {
self.root.commit(&mut acc);
self.root.commit(&mut buffer, &mut acc);
}

acc
let updates: Vec<(NodeHash, Vec<u8>)> = acc
.iter()
.map(|(hash, range)| (*hash, buffer[range.clone()].to_vec()))
.collect();
updates
}

/// Obtain a merkle proof for the given path.
Expand Down
Loading