Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 450
Alexis Wilke Avatar asked Jan 01 '26 12:01

Alexis Wilke


1 Answers

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

like image 131
Darren Cook Avatar answered Jan 03 '26 03:01

Darren Cook



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!