miktam / sizeof

Get size of a JavaScript object
MIT License
301 stars 45 forks source link

more precise string measurement for node platform #68

Closed quinlanj closed 1 year ago

quinlanj commented 2 years ago

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

Of 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 and require objects will give us a good idea. Source: https://www.geeksforgeeks.org/how-to-check-the-current-runtime-environment-is-a-browser-in-javascript/

tabarra commented 1 year ago

@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?