Hi there,
I’m very new to Julia. I’m not even sure this is the right place for asking my question. Let me know if it isn’t! (Btw if I have further questions that relate to Jupyter or Pluto, should I ask them elsewhere?)
My question is about when objects are copied, and when they are not.
(1) I read somewhere that “assignments never create copies”. So x= y
should absolutely never allocate more memory. Is that really a formal rule of the language, that I can count on?
It seems natural for mutable objects (you know that changing x will change y and vice-versa), but for immutable objects, it’s harder to believe. So x= 5; y= x
will cause y
to point to the exact same memory block as x
?? (Immutable objects can be huge, of course, so this can matter…)
(2) I have made some experiments, and it seems that, when you call a constructor, and the fields are immutable, then copies are, this time, made (with one exception, see below). Say
struct TwoInts
a::Int64
b::Int64
end
Then if x= 5
and you try TwoInts(x,x)
, it seems that the memory allocated is that needed for two ints, not just one (I’m using Base.summarysize
for this, which may be wrong…). So copies are made, and calling a constructor is very different from an assignment. Just wanted to check with you that I’m not talking nonsense up to here.
Also, if the fields are of mutable type, no copies are made.
All this is what I expected, I guess, but since I expected something perhaps different with x= y
, I’m checking
(3) Strings are an exception, it seems! Say
struct TwoStrings
a::String
b::String
end
Try then s= "a sufficiently long piece of string"
. Then the size of TwoStrings(s,s)
is less than twice the size of s
(!). Also, TwoStrings(s, "")
takes more space than TwoStrings(s,s)
(!!!).
What’s going on? I appreciate that strings are perhaps optimized in various ways, it’s only natural – but still, it would be an exception to the rule “calling a constructor makes copies for the fields of immutable type”, and that’s confusing.
Thanks for your help!
Pierre