Data Structures & Algorithms / Module 1: Linear data structures

Topic 1.3

Arrays vs linked lists in practice

Why arrays almost always win on real computers, even though linked lists look better on paper.

7 min · beginner

Watch: fetch item 4. The array jumps straight there in one step; the linked list has to walk from the start.

012345492751
  • moving now
  • finished / the result
Step 1 of 2

Array elements sit side by side in memory. The address of element i can be worked out directly: start + i × size.

An array works out where the element is and goes straight there. A linked list has to follow the pointers one by one.
store as:

One cupboard vs houses all over town

An array is like one cupboard with shelves in a row: take one book and the books next to it are right there. A linked list is like books left at different houses all over town, with every house giving the address of the next. To read them all you have to drive around town.

Computers work much the same way. When they read one piece of data from memory, they pull the area around it into a small, very fast store (the cache). With an array the next item has usually come along already. With a linked list every node can be somewhere else, so the computer often has to make the long trip again.

So when do you use which?

  • Use an array for almost everything: lists, queues as circular buffers, stacks, query results. Reading in order and reading random positions are both fast.
  • Consider a linked list when you keep inserting and removing in the middle of large data, and you already hold the node (through a hash map, say). An LRU cache is the classic example.
  • When in doubt, measure. The same Big-O doesn't mean the same speed. An array with O(n) shifting often still beats a linked list for data up to thousands of elements.

Quiz

  1. Why is reading an array from start to end usually faster than a linked list with the same number of elements?

  2. Reading the element at index 4: how many steps for an array, and for a linked list?

  3. The most sensible default for storing a list of data in an app is…

0 of 3 answered.