2 ms·
In languages that have immutable string semantics and can detect that they are the exclusive owner of a string, they can modify them in place. For reference cou
by MarkSweep 5y ago
In languages that have immutable string semantics and can detect that they are the exclusive owner of a string, they can modify them in place. For reference counting languages like Python, they can easily determine they are the exclusive owner by checking for a reference count of 1. See:
https://github.com/python/cpython/blob/main/Objects/unicodeobject.c#L11544 https://github.com/python/cpython/blob/main/Objects/unicodeo...
Rust's ownership system ensures that there cannot exist mutable and immutable references to the same object at the same time. So if you have a mutable reference to a string it is ok to modify in place.
I have not confirmed either the Python example or the Rust example too deeply, since I'm replying to 5 day old comment. But the general principal holds. GC languages like C# and Java don't have easy ways to check ownership so they always copy strings when mutating them. Maybe I'll write a blogpost on this in the future.