Skip to content

Commit 7ac5a55

Browse files
committed
Improve f64 encoding
Copy the bytes into a buffer instead of destructuring them. On my machine it's an about 15% performance improvement. A benchmark was added, which can be run via cargo bench --bench f64_enc --features use_alloc
1 parent 30fe080 commit 7ac5a55

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

Cargo.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,9 @@ name = "de"
4242
path = "benches/bench_de.rs"
4343
harness = false
4444
required-features = [ "serde1" ]
45+
46+
[[bench]]
47+
name = "f64_enc"
48+
path = "benches/f64_enc.rs"
49+
harness = false
50+
required-features = [ "use_alloc" ]

benches/f64_enc.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
use std::hint::black_box;
2+
3+
use cbor4ii::core::{enc::Encode, utils::BufWriter};
4+
use criterion::{criterion_group, criterion_main, Criterion};
5+
6+
fn bench_f64_enc(c: &mut Criterion) {
7+
c.bench_function("f64-enc", |b| {
8+
let float: f64 = 12345.6778;
9+
b.iter(|| {
10+
let mut writer = BufWriter::new(Vec::new());
11+
black_box(float.encode(&mut writer).unwrap());
12+
})
13+
});
14+
}
15+
16+
criterion_group!(f64_enc, bench_f64_enc);
17+
criterion_main!(f64_enc);

src/core/enc.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -376,8 +376,9 @@ impl Encode for f32 {
376376
impl Encode for f64 {
377377
#[inline]
378378
fn encode<W: Write>(&self, writer: &mut W) -> Result<(), Error<W::Error>> {
379-
let [x0, x1, x2, x3, x4, x5, x6, x7] = self.to_be_bytes();
380-
writer.push(&[marker::F64, x0, x1, x2, x3, x4, x5, x6, x7])?;
379+
let mut buf = [marker::F64, 0, 0, 0, 0, 0, 0, 0, 0];
380+
buf[..8].copy_from_slice(&self.to_be_bytes());
381+
writer.push(&buf)?;
381382
Ok(())
382383
}
383384
}

0 commit comments

Comments
 (0)