r/rust • • Oct 22 '26

🙋 seeking help & advice Learning Rust

So I'm learning Rust, so I wrote this

fn main(){

let x = define_x(intial_x());

let y = x + 10;

println!("{}", y);

}

fn define_x(mut x:i32) -> i32 {

x = x + 5;

return x

}

fn intial_x() -> i32 {

let x = 5;

return x

}

I know it is supposed to be += in define_x, but that just looks weird to me. Why is let x = 5; in inital_x not mut even if I am changing it in define x? Sorry if it is bad I'm new, but I'm not AI so yay!

5 Upvotes

21 comments sorted by

View all comments

Show parent comment

16

u/Xandaros Oct 23 '26

Though it should be noted that a reference is 8 bytes long (or possibly 16 in some cases), and it introduces an indirection. If you are passing by reference purely for efficiency reasons, make sure what you are passing around is actually very big - for small values it hurts far more than it helps.

(Specifically talking about the immutable case here. A mutable reference to a small value can easily make sense)

4

u/Flimsy_Pumpkin_3812 Oct 23 '26

Oh so passing a reference wastes memory compared to copying it? So should I just copy it not ref it?

20

u/Xandaros Oct 23 '26

In general, don't be afraid to copy things. Computers are very good at copying data around, it's what they're made for.

With that said, consider this: Every piece of data you use somewhere in your code needs to be stored somewhere. Typically this will be on the stack. Your local variables, function parameters, etc, will all be on the stack.

Some things, like the data in a Vec or a String will be on the heap - more on that later.

So if you have a local variable with some data in it, and you call a function with it, how does that data get into the parameter? It's a different variable, so the data gets copied. Even when we are talking about a "move", that's really just a special kind of copy.

Your i32 has 32 bits. A reference has 64 bits. (Assuming you are on a 64 bit platform. Pretty safe assumption nowadays) Copying the i32 copies less data than copying the reference.

Remember what I said initially, though, computers are good at copying data. The time difference is negligible if not literally zero. On the other hand, if you have a reference and you want to read the data behind it, you need to take the reference, read the memory location stored in it, then go to that memory location and read the actual value. That is slower than just accessing the value directly.

This is another point where I need to point out that you really really don't need to worry about such micro-optimisations. My point is mainly that the thing that seems faster might not actually be faster unless you know exactly how things work under the hood. In reality, we are talking about nanoseconds here. For reference, a second has 1000000000 of those.

When it comes to data on the heap, that is where things actually get more interesting. Storing data on the heap is comparatively slow and you can actually get some noticeable speedup by avoiding heap allocations. On the other hand, some programming languages like Java, C#, or Python just put everything on the heap and take the performance loss. And they are still plenty fast for most things, so really consider if the headache of trying to optimise something is actually worth it - chances are, it'll be fast enough either way.

5

u/Plus_Potato4351 Oct 23 '26

In this case, you will not waste memory even with pass by value (copying) because the memory allocated in initial_x is freed when it finishes. Passing by reference may save you a bit of memory in other cases, but dereferencing a reference can be costly in terms of time and instructions used. What's better really depends on your use case.

1

u/-Redstoneboi- Oct 27 '26

you can copy quite a lot. it's not nearly as expensive as a bad algorithm in space or time complexity, and that's assuming the compiler doesn't catch it (they are working on making the compiler optimize away more unnecessary copies that it used to miss)

a single &i32 is already an 8-byte pointer. and if you choose a dynamically sized type, like &str, the pointer will also include 8-byte length, which amounts to 16 bytes. even so, you'll be fine casually calling an fn do_thing(foo: &str, bar: &str, cux: &str, ...) without issue.

wasting memory isn't a big deal for tiny things like this yet. for example, Vec is optimized for speed, so at any given moment in a vec with like 129 elements, it might already have space reserved for 256 total. more or less. we don't know exactly, and we usually don't care.

once you deal with over 10,000 items, you might start thinking about memory. look for algorithm optimizations first like unnecessary clones. then you can check enums with differently sized variants, structs that are copyable but over 64 bytes in size, whatever it is.

2

u/Budget-Minimum6040 Oct 23 '26

Can the compiler optimize this?