Skip to content

Commit 9e96e84

Browse files
committed
perf(MerkleTree): Initialize in parallel
1 parent 02720be commit 9e96e84

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

twenty-first/src/util_types/merkle_tree.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::borrow::Cow;
22
use std::collections::hash_map::Entry::*;
33
use std::collections::*;
44
use std::fmt::Debug;
5+
use std::mem::MaybeUninit;
56
use std::result;
67

78
use arbitrary::*;
@@ -398,7 +399,21 @@ impl MerkleTree {
398399
nodes
399400
.try_reserve_exact(num_nodes)
400401
.map_err(|_| MerkleTreeError::TreeTooHigh)?;
401-
nodes.resize(num_nodes, Digest::default());
402+
403+
// Parallel initialization is slower for small trees, but faster for
404+
// tall trees. If the slowdown is deemed too big for small trees, this
405+
// is the place to change it.
406+
nodes
407+
.spare_capacity_mut()
408+
.par_iter_mut()
409+
.take(num_nodes)
410+
.for_each(|n| *n = const { MaybeUninit::new(Digest::ALL_ZERO) });
411+
412+
// SAFETY:
413+
// - the requested capacity is num_nodes, and so is the new length
414+
// - the first num_nodes elements are initialized to Digest::ALL_ZERO
415+
unsafe { nodes.set_len(num_nodes) };
416+
402417
nodes[num_leafs..].copy_from_slice(leafs);
403418

404419
Ok(nodes)

0 commit comments

Comments
 (0)