
V8 memory quiz - mostlystatic
http://www.mattzeunert.com/2018/01/25/v8-javascript-memory-quiz.html
======
bakery2k
Spoiler: V8's default array implementation holds pointers to boxed objects
[Questions 5 & 6], but there are special-case implementations for arrays of
doubles [1] and 16-bit integers [9] (and presumably others). However, adding a
single string to an array of doubles violates the special-case and requires
every double to be boxed, significantly increasing memory footprint [2].

It's interesting to compare this to a "NaN-boxing" approach, which allows
pointers and doubles (and other simple values) to all exist in a single
"namespace" of 8-byte values. In the (uncommon?) case of a heterogeneous
array, this can save memory by avoiding the need to box simple values. The
downside is that NaN-boxing prevents the use of full 64-bit pointers.

~~~
GlitchMr
This isn't a special cased array specialization for 16-bit integers (16-bit
integers are so rare that special casing those is not worth it). Note that a
standard array is not used in [9], rather an `Int16Array` is being used. Due
to JavaScript specification requirements (arrays of different integer sizes
can share storage), the ONLY sane implementation of Int16Array is well... an
array of 16-bit integers.

------
Waterluvian
This is one of my favourite ways to play with a concept. The quiz part forces
my brain to turn on the problem solving section rather than just the reading
section.

------
amelius
Okay, but how about other JavaScript engines?

And shouldn't stuff like this be in the specs, so that the language becomes
more consistent and predictable?

~~~
pcwalton
> Okay, but how about other JavaScript engines?

SpiderMonkey uses NaN-boxing, so pointers to objects will sometimes take up
less space than in V8. As for hidden classes, I'm not sure about how shapes
(SpiderMonkey's term for hidden classes) interact with constructors.

> And shouldn't stuff like this be in the specs, so that the language becomes
> more consistent and predictable?

That would stifle compiler innovation. Not even the "low-level", "predictable"
C and C++ mandate particular implementations, beyond specifying the bare
minimum necessary to ensure pointer arithmetic works portably.

~~~
amelius
> Not even the "low-level", "predictable" C and C++ mandate particular
> implementations

But at least with C and C++ a developer can test the performance before
deployment.

------
aiCeivi9
So V8 doesn't use compressed pointers? It sounds wasteful to use whole 8 bytes
for pointer if typical JS application is unlikely to need more than 2GB of ram

------
mcguire
The default size of an array for V8 is over 1304209 elements?

~~~
minitech
When it runs out of space, it resizes to (at least) a multiple of its current
space to avoid having to resize too often, making pushing a constant-time
operation on average. 1304209 is the smallest size in the sequence starting
with an empty array that’s at least 1048576.

