Bug or optimisation

The following code:
struct A:
fn __init__(inout self): ...

fn main():
print(UnsafePointer.address_of(A()) == UnsafePointer.address_of(A())) # Prints True
struct A:
fn __init__(inout self): ...

fn main():
print(UnsafePointer.address_of(A()) == UnsafePointer.address_of(A())) # Prints True
indicates that both initialised empty struct has the same address. Are empty structs automatically "singleton"? Or is it a bug in the compiler? I am using Mac M1.
4 Replies
ivellapillil
ivellapillil2mo ago
mojo 24.4.0 (2cb57382)
Darkmatter
Darkmatter2mo ago
This looks like the compiler is seeing that the constructor is pure and deciding to de-duplicate it because you never modify either instance.
ivellapillil
ivellapillil2mo ago
Thanks! I was not aware compilers perform this optimisation.
Darkmatter
Darkmatter2mo ago
Compilers like to look for places to de-duplicate work because you can save a lot of processing if you can pull it off. In your case it’s trivial work, but if each constructor needed to calculate the first 200 primes or something like that, you would see noticeable performance increases.
Want results from more Discord servers?
Add your server