2 ms·
> No, primitives are immutable but still passed by reference For immutable values the pass-by-reference vs pass-by-value distinction isn't really important. Un
by kevincox 4y ago
> No, primitives are immutable but still passed by reference
For immutable values the pass-by-reference vs pass-by-value distinction isn't really important. Unless the language provides some way to get the identity of the object there isn't a way to tell a difference.
> Can you imagine if we'd copied strings every time they were passed into a function?
IIUC most Javascript interpreters optimize copying strings anyways, so this wouldn't be a big deal. For example even though `s.slice(1)` is a "copy" most engines (I believe V8 included) will use the same backing string for both. So the difference would be a pointer on the stack vs a pointer+length on the stack and copying an extra word is not a huge difference.
But maybe this is just being nitpicky, since the article is focused on performance the lower level details do mater not the semantics. However for strings I don't think the difference between their model and reality is very significant.
- Leszek 4y agoYou're talking about semantics and you're totally right, there's plenty of cases in the implementation where things are not copied when they should be (string slices) or copied when they shouldn't be (boxed double writes into mutable double boxes). As you say though, the semantics are kind of irrelevant when you're talking about actual memory behaviour of allocations. There's actually lots of really interesting consequences of the current implementation, and the various tricks it does around what's observable and what's fast, it's just not what's described here.
- koolba 4y ago> For example even though `s.slice(1)` is a "copy" most engines (I believe V8 included) will use the same backing string for both. That’s not a copy, it skips the first character!
- kevincox 4y agoIt's semantically a copy of most of the string.