Hacker News new | ask | show | jobs
by kaeluka 4113 days ago
If I remember Bjarne's talk correctly, vectors (in C++) are even fast at inserting because they have densely packed representation which rhymes well with modern computer architecture. Inserting in a linked list is slow, as walking the list to find the element at which to insert will already incur O(N) cache misses, whereas in vectors it's only O(1) cache misses. Moving the elements in the vector one to the right is fast due to computer architecture dealing well with predictable patterns.

The allocations here (ruby) are reduced because the implementation of appending is horribly slow in the first place, using defensive cloning (I'm taking jph's word here).

1 comments

Yes, but FWIW most linked list implementations have a reference or pointer to the tail, making appends not O(n), but O(1). However, there is a threshold, depending on use case, where a small vector being resized multiple times larger than the original will be faster than many linked list appends. Point being, either can accel depending on use case.