Can declaring a field as const in a mutable struct require less memory?

Currently declaring a field as const in a mutable struct doesn’t seem to do anything:

julia> mutable struct A
           x::Int
       end

julia> mutable struct B
           const x::Int
       end

julia> @allocated A[A(i) for i in 1:1000] # all ints are different
24128

julia> @allocated B[B(i) for i in 1:1000] # all ints are different
24128

julia> @allocated A[A(1) for _ in 1:1000] # all ints are 1
24128

julia> @allocated B[B(1) for _ in 1:1000] # all ints are 1
24128

Intuitively, I would think that the fourth case could reuse the memory for the 1s and so should allocate less. Is this something feasible?

The const field doesn’t imply that it is a constant at compile-time, which means that the compiler is not expecting that the values are all the same here and doesn’t try to do such optimizations.

Technically, you might be able to do that with the Val type, which is constant at compile-time.

2 Likes

No matter whether all fields are const or not, object identity between mutable instances must still be distinct. That is their defining feature after all!

4 Likes

If it reused the memory it would have to fetch the value using the reference all the time, and the struct would have to carry the reference. Actually declaring it const more about the opposite: you promise to the compiler that the value does not change, and it can do whatever it thinks is more appropriate with it’s storage to improve the performance of the code.

2 Likes

thanks guys, seems like my intuition was off :slight_smile: