javascriptcopy-on-write

JavaScript and large strings, is JavaScript using copy-on-write?


I would like to know (confirm, hopefully) whether JavaScript manages its variable in a copy-on-write manner. This is important because I may end up dealing with possibly large strings, quite a few of them.

var a, b;

a = $(".foo").html();
b = a;

Is b a deep copy or a copy-on-write? My code would benefit very much from a copy-on-write because in some cases I set b to a different value (i.e. in most cases I copy a, in other cases I set to, for example, "on" or "off". However, it doesn't get modified later.)


Solution

  • 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