Which way is more optimal?
a:
let data: &'_ Data = &Data::new();
any(data);
any(data);
any(data);
b:
let data: Data = Data::new();
any(&data);
any(&data);
any(&data);
Which way is more optimal?
a:
let data: &'_ Data = &Data::new();
any(data);
any(data);
any(data);
b:
let data: Data = Data::new();
any(&data);
any(&data);
any(&data);
They will generate exactly the same machine code, but the second is better/more conventional Rust style I'd say.
The first one is a contract: it's telling me that you never will mutate data.
So I would go for it if possible.
The first also has the downside (or possibly upside, in some situations) that the data can't escape the current stack frame... which means it's not only an a-or-b sort of choice, since they are not equivalent. (apart from this specific micro example, or the case where &_
is actually &static
)
The second one mostly provides that already by not being let mut
. I would prefer the first because it doesn't rely on implicit lifetime extension, which is a fairly weird feature in my opinion.
You can easily mutate data in second one by rebinding it via let mut.
The first one gives you no* possibility to do so.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.