Internally, V8 stores strings using 1 byte per ASCII char with an additional 12 byte header. The size of any heap object must be a multiple of the pointer size, i.e. a multiple of 4, so the size of the string is rounded up to that; the last few bytes may be unused. Therefore the size of a string is calculated the following way: 12 + 4 * Math.ceil(n/4). Source: https://stackoverflow.com/questions/68789144/how-much-memory-do-v8-take-to-store-a-string/68791382#68791382
@miktam Any thoughts on this PR? Considering most would use this package in node I feel like this is a must.
@quinlanj Probably better to also add a note about this important detail on README.md?
Internally, V8 stores strings using 1 byte per ASCII char with an additional 12 byte header. The size of any heap object must be a multiple of the pointer size, i.e. a multiple of 4, so the size of the string is rounded up to that; the last few bytes may be unused. Therefore the size of a string is calculated the following way:
12 + 4 * Math.ceil(n/4)
. Source: https://stackoverflow.com/questions/68789144/how-much-memory-do-v8-take-to-store-a-string/68791382#68791382Of course, this is not true in other javascript runtimes, so it's better to use the default approximation in that case. There is no surefire way to detect node runtime, but looking at
process
andrequire
objects will give us a good idea. Source: https://www.geeksforgeeks.org/how-to-check-the-current-runtime-environment-is-a-browser-in-javascript/