I’m afraid the clone() method does result in memory allocation. I test these methods:
fn main() {
let t1=std::time::Instant::now();
let mut my_string=String::new();
let a=“aaa”;
let b=“bbb”;
let c=“ccc”;
for _ in 0..1000000 {
my_string.push_str(a);
my_string.push_str(b);
my_string.push_str(c);
my_string.clear();
}
println!("{:?}", t1.elapsed());
}
three times:
Duration { secs: 0, nanos: 3670486 }
Duration { secs: 0, nanos: 3342101 }
Duration { secs: 0, nanos: 3224247 }
fn main() {
let t1=std::time::Instant::now();
let mut my_string=String::new();
let a=“aaa”;
let b=“bbb”;
let c=“ccc”;
for _ in 0..1000000 {
my_string=[a, b, c].concat();
}
println!("{:?}", t1.elapsed());
}
three times:
Duration { secs: 0, nanos: 81928727 }
Duration { secs: 0, nanos: 77676702 }
Duration { secs: 0, nanos: 78448896 }
fn main() {
let t1=std::time::Instant::now();
let mut my_string=String::new();
let a=“aaa”;
let b=“bbb”;
let c=“ccc”;
for _ in 0..1000000 {
my_string=[a, b, c].into_iter().cloned().collect::<String>();
}
println!("{:?}", t1.elapsed());
}
three times:
Duration { secs: 0, nanos: 353488365 }
Duration { secs: 0, nanos: 260228488 }
Duration { secs: 0, nanos: 323822175 }
fn main() {
let t1=std::time::Instant::now();
let mut my_string=String::new();
let a=“aaa”;
let b=“bbb”;
let c=“ccc”;
for _ in 0..1000000 {
my_string.extend([a, b, c].into_iter().cloned());
my_string.clear();
}
println!("{:?}", t1.elapsed());
}
three times:
Duration { secs: 0, nanos: 42792508 }
Duration { secs: 0, nanos: 39719744 }
Duration { secs: 0, nanos: 46006185 }
As you see, the push_str() is more than ten times faster than the others.