r/learnprogramming • • Jan 31 '14

Can someone ELI5 linked lists?

Part of my assignment for my online class involves linked lists and we don't really go over them. I looked around online and I'm slightly confused by all the explainations since I'm fairly new to programming. Can someone dumb it down for me?

77 Upvotes

85 comments sorted by

View all comments

Show parent comment

1

u/Jonny0Than Feb 01 '14 edited Feb 01 '14

In practice, this is actually wrong:

The array will take much, much longer, because it has to physically move half of the list.

Cache coherency dominates in a lot of unexpected places, and can overcome algorithmic complexity when the unit of work is relatively small.

When you were hopping through half your list to find the right spot to insert, you were missing memory cache all over the place. Finding the middle of an array is trivial. And moving all that data? It's all adjacent so there are very few cache misses, and it's way faster than you'd expect.

I didn't believe this the first time I heard it, but I wrote some test programs and it's actually true.

For an apples-to-apples test, fill an array and a list with integers 0-999,999 and randomly shuffle them. Then pick a number at random, find it, and remove it from the container. When the number is near the beginning of the container, the list will be faster. Last time I tried this the list won when the number was in the first 25% of the container, and the array was faster otherwise.

1

u/door_of_doom Feb 01 '14

Fascinating! What language were you running the test in?