Hacker News new | ask | show | jobs
by pedrocr 4567 days ago
Why does "str2 = str" actually allocate a new RString instead of just pointing both str and str2 to the same RString?
2 comments

That's what it is doing. The additional RString structure associates the label "str2" with the characters (on the heap) allocated for the original string.

Ruby experts can correct me if I'm wrong, but when Ruby sees a name like "str2" it looks it up in a table, which points it to the RString structure. From there, it can follow the pointer to the actual array of characters, which in this case is only stored once.

According to the article both str and str2 will point to the same char[] on the heap, but they are represented by two different RString objects. As you said when you want to access str and str2 you need to look them up in a table. So why not have both entries on the table point to the same RString, instead of pointing to two different RString's that point to the same char[]?
I'm sorry, I misunderstood your question. Apparently what you describe is actually the case, as the link posted by danieldk below describes.
I haven't checked the code so I may be wrong but it's possible it's for multi-threading reasons.
MRI has a global interpreter lock, so that does not make much sense.

In fact, the diagram is simply wrong. This was rectified by the author in an article two weeks later:

http://patshaughnessy.net/2012/1/18/seeing-double-how-ruby-s...