Which way is more optimal?

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.

6 Likes

The first one is a contract: it's telling me that you never will mutate data.

So I would go for it if possible.

1 Like

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)

3 Likes

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.

1 Like

You can easily mutate data in second one by rebinding it via let mut.
The first one gives you no* possibility to do so.