format!
allocates a new heap(?) String
for us, which can be further passed to a println!
:
let thing: String = format!("I have {} cats.", 6};
println!("My message is: {}", thing);
But of course we could have just:
println!("My message is: I have {} cats.", 6);
Is the former necessarily less efficient than the latter?
Let's add a new element, then:
fn declaration(msg: String) {
println!("My message is: {}", msg);
}
and who knows where that external String
actually came from.
Will Rust/LLVM see what's happening in either case, and optimize down to something nice? I suppose I feel this way every time I use a String
or &str
as an argument to format!
or println!
. Are we punished for the "String embedding"?