Do JavaScript strings use copy-on-write? No, because you cannot write to a JavaScript string, they are immutable.
But, yes, they are effectively using that optimization. When you assign b=a
in your example, b
is getting a pointer to the same storage that a
is pointing to. I.e. it is very quick. If you then do b = b.replace('x','y')
, a new string is created, and b
points to it, while a
continues to point to the original string.
See section 11.2.2 in JavaScript The Definitive Guide, on strings.
BTW, if you are really interested, here are the V8 sources:
https://github.com/v8/v8/blob/master/src/objects/string.h
https://github.com/v8/v8/blob/master/src/objects/string.cc
And a bit of explanation as to why it is so complex (i.e. large strings are sometimes stored as a bunch of small strings, which are only reassembled when necessary; there also seems to be an optimization for ascii strings) https://gist.github.com/mraleph/3397008