Hacker News new | ask | show | jobs
by josephg 1318 days ago
A c++ vector internally uses an array - which is a chunk of memory where each item is just in the next spot in memory in sequential order. Eg, the array [1,2,3] might have 1 at memory address 100, 2 at memory address 101 and 3 at memory address 102. Given an array index, you can figure out where a value is stored in memory pretty trivially.

When the array fills up, vector will allocate a fresh array (thats bigger - often 2x bigger) and copy everything over. This is slow - because it has to copy everything. But much faster than you think.

So thats how C++'s vector (and Rust's Vec) work.

Javascript implementations (like v8) can swap out the implementation behind the scenes based on how you're using your array. The API is always the same - but the way the array works in memory will be different based on whatever is fastest given the way you're using your array. (V8 doesn't know ahead of time what sort of data will be in your array or what you're using it for, so it guesses then changes things up if it guesses wrong).

Here's a blog post talking about some of the internal details in V8:

https://itnext.io/v8-deep-dives-understanding-array-internal...

The actual implementation is much more complex than this blog post suggests. (I think they also optimize based on push/pop vs shift/unshift vs other stuff).

1 comments

Thanks for taking the time to write that up–I appreciate the explanation.

My only adjacent knowledge here was when I checked the V8 implementation of the `sort` method on the array prototype and saw it changes the sorting algorithm used based on array length (IIRC insertion sort for length < 10 and merge sort otherwise).

Thanks for the V8 resource as well.