perf(trie): prealloc in Nibble::unpack (#5629)

This commit is contained in:
Vitaly Drogan
2023-11-29 22:22:04 +01:00
committed by GitHub
parent 471c28e889
commit e9dfd059dd
3 changed files with 28 additions and 7 deletions

View File

@ -99,3 +99,7 @@ harness = false
name = "trie_root"
required-features = ["arbitrary", "test-utils"]
harness = false
[[bench]]
name = "nibbles"
harness = false

View File

@ -0,0 +1,19 @@
use criterion::{criterion_group, criterion_main, Criterion};
use reth_primitives::trie::Nibbles;
/// Benchmarks the nibble unpacking.
pub fn nibbles_benchmark(c: &mut Criterion) {
c.bench_function("Nibbles unpack", |b| {
let raw = (1..=32).collect::<Vec<u8>>();
b.iter(|| {
Nibbles::unpack(&raw);
})
});
}
criterion_group! {
name = benches;
config = Criterion::default();
targets = nibbles_benchmark
}
criterion_main!(benches);

View File

@ -94,14 +94,12 @@ impl Nibbles {
/// Take a byte array (slice or vector) as input and convert it into a [Nibbles] struct
/// containing the nibbles (half-bytes or 4 bits) that make up the input byte data.
pub fn unpack<T: AsRef<[u8]>>(data: T) -> Self {
Nibbles {
hex_data: Bytes::from(
data.as_ref()
.iter()
.flat_map(|item| vec![item / 16, item % 16])
.collect::<Vec<u8>>(),
),
let mut vec = Vec::with_capacity(data.as_ref().len() * 2);
for byte in data.as_ref() {
vec.push(byte / 16);
vec.push(byte % 16);
}
Nibbles { hex_data: Bytes::from(vec) }
}
/// Packs the nibbles stored in the struct into a byte vector.