Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Rust reuse memory with same value

Example code:

fn main() {
    let mut y = &5; // 1

    println!("{:p}", y);

    {
        let x = &2; // 2
        println!("{:p}", x);
        y = x;
    }

    y = &3; // 3
    println!("{:p}", y);
}

If third assignment contains &3 then code output:

0x558e7da926a0
0x558e7da926a4
0x558e7da926a8

If third assignment contains &2 (same value with second assignment) then code output:

0x558e7da926a0
0x558e7da926a4
0x558e7da926a4

If third assignment contains &5 (same value with first assignment) then code output:

0x558e7da926a0
0x558e7da926a4
0x558e7da926a0

Why does rust not free memory but reuse it if the assignment value is the same or allocate a new block of memory otherwise?

like image 384
TupleCats Avatar asked Jan 01 '23 13:01

TupleCats


2 Answers

Two occurrences of the same literal number are indistinguishable. You cannot expect the address of two literals to be identical, and neither can you expect them to be different.

This allows the compiler (but in fact it is free to do otherwise) to emit one 5 data in the executable code, and have all &5 refer to it. Constants may (see comment) also have a static lifetime, in which case they are not allocated/deallocated during program execution, they always are allocated.

like image 93
coredump Avatar answered Jan 03 '23 02:01

coredump


There are lots of tricks an optimizing compiler can use to determine if a variable can be assigned a constant value. Your findings are consistent with this, no need to run duplicate code if it is not needed.

like image 42
Simson Avatar answered Jan 03 '23 02:01

Simson