Skip to content

Commit

Permalink
add benchmarks
Browse files Browse the repository at this point in the history
This regressed from a previous attempt.
The worst of the old results were in the range 450.000

current:

test bench::bench_derive_clone ... bench:   1,653,247 ns/iter (+/- 32,781)
test bench::bench_match_clone  ... bench:   1,716,482 ns/iter (+/- 34,192)
test bench::bench_new_clone    ... bench:   1,717,985 ns/iter (+/- 52,137)
  • Loading branch information
AntonSol919 authored and Veykril committed Jan 31, 2024
1 parent 01114d2 commit 14cbe54
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![feature(core_intrinsics, test)]
#![no_std]
extern crate alloc;

Expand Down Expand Up @@ -33,7 +34,63 @@ use core::{
#[derive(Clone)]
pub struct SmolStr(Repr);

mod bench {
extern crate test;
use test::Bencher;
fn test_strings() -> [crate::SmolStr; 200] {
[0; 200].map(|_| crate::SmolStr::new("0123456780"))
}
#[bench]
fn bench_derive_clone(b: &mut Bencher) {
let it = test::black_box(test_strings());
b.iter(|| {
(0..1000)
.map(|_| it.iter().map(|e| e.clone()))
.flatten()
.filter(|o| o.is_heap_allocated())
.count()
})
}
#[bench]
fn bench_new_clone(b: &mut Bencher) {
let it = test::black_box(test_strings());
b.iter(|| {
(0..1000)
.map(|_| it.iter().map(|e| e.new_clone()))
.flatten()
.filter(|o| o.is_heap_allocated())
.count()
})
}
#[bench]
fn bench_match_clone(b: &mut Bencher) {
let it = test::black_box(test_strings());
b.iter(|| {
(0..1000)
.map(|_| it.iter().map(|e| e.match_clone()))
.flatten()
.filter(|o| o.is_heap_allocated())
.count()
})
}
}

impl SmolStr {

#[inline(always)]
pub fn new_clone(&self) -> Self {
if !self.is_heap_allocated() {
return unsafe { core::mem::transmute_copy(self) };
}
Self(self.0.clone())
}
#[inline(always)]
pub fn match_clone(&self) -> Self {
match &self.0 {
Repr::Heap(h) => return Self(Repr::Heap(h.clone())),
_ => unsafe { core::mem::transmute_copy(self) },
}
}
#[deprecated = "Use `new_inline` instead"]
pub const fn new_inline_from_ascii(len: usize, bytes: &[u8]) -> SmolStr {
assert!(len <= INLINE_CAP);
Expand Down

0 comments on commit 14cbe54

Please sign in to comment.