Comment by reificator

5 years ago

> > If the array is sorted it can be binary searched to get to the change point, which improves its performance even more, linked lists can’t do that.

> And if you not doing ordered insertion you wouldn't have to move the data in the array anyway, you would keep track of the size and jump to the end, so not sure I understand the binary search comment.

It just means that if I want to view the nth element of an array, that's a constant time operation. I just take the pointer and add n times the size of the elements.

But for a linked list if I want to view the nth element of the list, I have to view the (n-1)th element first, all the way back until the first element I have a reference to.

> The next question is at what level of growth the waste of empty space in the array becomes too much.

Everything I've tried and everything I've seen from people testing on real hardware is that the gap in performance widens with larger values of n.

You might expect different performance as the system runs out of memory. But arrays have a size of n * element size, and linked lists have a size of n * (pointer(s) + element size), so the linked list would hit memory limitations more quickly regardless.

But the memory usage isn't considering growth. If I grow by doubling the size (seems common) at n+1 element where n is the last allocation, one would allocate n2 + n (the original until the copy finishes) vs. n (pointer(s) + element size).

But yes the size advantage is very reduced for most use cases. What would you imagine the cases where LinkedList is still a valid data structure?

  • > If I grow by doubling the size (seems common)

    True. Then it comes down to the size of your data vs the size of your pointers.

    > What would you imagine the cases where LinkedList is still a valid data structure?

    Compared to an array? When the array doesn't have the behavior that you need.

    For instance, if you need to keep a stable reference to a particular element in a list, even while that list is being inserted into, then an array is not going to cut it. The linked list handles this case with ease.

    That's not to say you can't write a wrapper for the array that does the right thing, probably for cheaper. But out of the box the linked list can do things that the array cannot and if you rely on them, then use the right tool for the job.