use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
use std::{borrow::Cow, hint::black_box};
fn sample_data() -> Vec<&'static str> {
vec![
"",
"a",
"hello",
"rustacean",
"The quick brown fox jumps over the lazy dog",
"The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog",
"🚀✨🦀",
"🚀✨🦀🚀✨🦀🚀✨🦀🚀✨🦀🚀✨🦀🚀✨🦀",
]
.into_iter()
.collect()
}
fn bench_to_owned(c: &mut Criterion) {
let data = sample_data();
let mut g = c.benchmark_group("str_clone_methods");
g.bench_function("to_owned", |b| {
b.iter_batched(
|| data.clone(),
|inputs| {
let v: Vec<String> = inputs.into_iter().map(|s| s.to_owned()).collect();
black_box(v);
},
BatchSize::SmallInput,
)
});
g.bench_function("to_string", |b| {
b.iter_batched(
|| data.clone(),
|inputs| {
let v: Vec<String> = inputs.into_iter().map(|s| s.to_string()).collect();
black_box(v);
},
BatchSize::SmallInput,
)
});
g.bench_function("Cow::<str>::from + into_owned", |b| {
b.iter_batched(
|| data.clone(),
|inputs| {
let v: Vec<String> = inputs
.into_iter()
.map(|s| Cow::from(s).into_owned())
.collect();
black_box(v);
},
BatchSize::SmallInput,
)
});
g.finish();
}
criterion_group!(benches, bench_to_owned);
criterion_main!(benches);
1
共 4 条评论, 1 页
评论区
写评论确实,使用rustc生成asm汇编指令,对比
str::to_owned()
、str::to_string()
、<String as From<&str>>::from()
、Cow::<'_, str>::into_owned()
四个函数的指令,除了个别伪指令标记的区别,其他 cpu指令都是完全一样的没有太大意义,差异应该是噪音,to_string最后还是调用to_owned,汇编也直接等同于to_owned(https://godbolt.org/z/ajPaqxbGe)
->
->
->
移动5800h
--
👇
lxl66566: 啥设备 贴下结果?
str_clone_methods/to_owned [505.60 ns 520.51 ns 536.14 ns] str_clone_methods/to_string [513.66 ns 541.82 ns 576.73 ns] str_clone_methods/Cow::::from + into_owned [500.66 ns 516.39 ns 532.23 ns]
啥设备 贴下结果?
str_clone_methods/to_owned [505.60 ns 520.51 ns 536.14 ns] str_clone_methods/to_string [513.66 ns 541.82 ns 576.73 ns] str_clone_methods/Cow::::from + into_owned [500.66 ns 516.39 ns 532.23 ns]