5 ms·
The optimization of reusing the character array for a string was used in Java until roughly the Java 7 days, when it was dropped because it could cause a space
by hyperpape 9y ago
The optimization of reusing the character array for a string was used in Java until roughly the Java 7 days, when it was dropped because it could cause a space leak: https://stackoverflow.com/questions/15612157/substring-method-in-string-class-causes-memory-leak#15612188 https://stackoverflow.com/questions/15612157/substring-metho....
One difference in Java was that you could slice out the middle of a string (you just kept the start and end of the array, iirc). I wonder if that difference makes this approach workable for Ruby, or if that implies that one team made a mistake.
- tenderlove 9y agoGood question, I'll have to read up on it. It looks like it's possible to share out of the middle of a string with MRI, but it requires certain compiler options that aren't on by default. Thanks for the comment! <3
- igravious 9y agoDoes this optimization mean we can dispense with Bootsnap? The magic Bootsnap does makes me fearful and it adds yet another moving part that can break :(
- aardvark179 9y agoIt’s not quite that simple. Java strings and ruby strings have quite different semantics because Java strings are immutable whilst Ruby strings are both mutable and can be mutated in place by C extensions. In Truffleruby we use ropes to represent strings which allow sharing of substrings and convert them to unique mutable ropes when they are accessed by C extensions, but that requires quite a lot of machinery to implement.
- hyperpape 9y agoI always forget that about ruby strings. However, I’m not sure I can think through how it changes the performance trade offs of sharing.
- aardvark179 9y agoWell, if strings are immutable then you can point into an array in the subsrring and the worst that can happen is a space leak. If your strings are mutable then you need some extra book keeping so that attempts to copy the parent or child won’t affect the other. Whether you get a gain from sharing is going to depend on the length of your strings and what operations you perform on them. If you are trying to reimplement an existing VM/standard library then you may also need to honour the expectations of developers. If they expect creating a substring to be an O(1) operation and code against that expectation then you probably need to honour it.
- tyingq 9y agoI wonder how Ruby string performance compares to Perl then. They seem to have the same constraints.