Rust code, it takes 5.23 seconds with --release and some rustc omptimizations (opt-level = 3, lto = true, codegen-units = 1):
fn id() -> &'static str{
// with_capacity is better than new
let mut ids_string=String::with_capacity(41);
for shape_id in 0..20 {
// &shape_id.to_string() is better than shape_id.to_string().as_str()
ids_string.push_str(&shape_id.to_string());
ids_string.push('/');
}
return Box::leak(ids_string.into_boxed_str());
}
fn main(){
let now = std::time::Instant::now();
for _ in 0..80_0000 {
let id=id();
}
let elapsed = now.elapsed();
println!("{:?}", elapsed);
}
Side-by-side Java code, it only takes 464 milliseconds:
public class test2 {
static String id() {
StringBuilder sb = new StringBuilder(41);
for (int shape_id = 0; shape_id < 20; shape_id++) {
sb.append(shape_id);
sb.append('/');
}
return sb.toString();
}
public static void main(String[] args) {
long t1=System.currentTimeMillis();
for(int i=0; i<80_0000; i++) {
String id=id();
}
long t2=System.currentTimeMillis();
System.out.println(t2 - t1);
}
}
Hopefully some experienced guys can make Rust outperform Java on this, otherwise I think I will be losing confidence in Rust.
Growing a String in a function and returning it as a &str as speedy as possible, this is what I need, but I didn't see any headroom to speed it up so far.