Your linked list is slower than your vector, and big-O will not tell you why

Here is a question with a wrong answer that every data structures course teaches.

You need a sequence. You will insert into the middle of it, often. Which do you choose: std::vector, where inserting in the middle is O(n) because every later element shifts, or std::list, where inserting is O(1) because you relink two pointers?

The textbook says std::list. Measure it, and for anything up to a few thousand elements of any ordinary size, std::vector wins — frequently by a factor of five or ten. It wins while doing more work by the count that the complexity analysis is measuring.

This is not a trick or a quirk of one compiler. It is the single most useful thing to understand about performance on modern hardware, and it generalises far beyond C++.

The machine big-O is describing

Complexity analysis counts operations. It assumes every memory access costs the same, because when the notation was settled that was approximately true: processors and memory ran at comparable speeds, and fetching a word was a handful of cycles whichever word you asked for.

That assumption stopped holding somewhere in the late eighties, and the gap has widened every year since. A modern processor runs at a few gigahertz. Main memory takes somewhere around 200 to 300 cycles to answer. In the time your CPU waits for one value from RAM, it could have executed several hundred instructions.

Hardware designers' response was the cache hierarchy. A small, very fast L1 cache — tens of kilobytes, maybe four cycles away. A larger L2, around a dozen cycles. An L3 shared between cores, forty or so. Then main memory, hundreds. Every access checks each level in turn, and the difference between finding your data in L1 and going to RAM is roughly two orders of magnitude.

Big-O counts both as one operation.

Cache lines, and why asking for one byte gets you sixty-four

Caches do not deal in individual bytes. They move cache lines, which on essentially every current processor are 64 bytes. Read one int that is not already cached, and the hardware fetches the entire aligned 64-byte block containing it.

For a std::vector<int>, that is extraordinary value. The elements are contiguous, so one cache line holds sixteen of them. Walk a vector and you pay for a memory fetch once every sixteen elements; the other fifteen are already sitting in L1, four cycles away.

It gets better. The prefetcher — a piece of hardware watching your access pattern — notices a sequential walk and starts fetching lines ahead of your request. On a clean linear scan, the data is frequently in cache before you ask, and the fetches cost nothing at all because they happened while the processor was busy with the previous elements.

Now the list. std::list<int> on a 64-bit platform stores each element in its own heap node: the int, plus a forward pointer, plus a back pointer. Four bytes of payload, sixteen bytes of pointers, and the allocator rounds that up — call it 32 bytes per node, of which 12% is your data.

Those nodes are wherever the allocator put them. If you built the list over the lifetime of a program, interleaved with other allocations, they are scattered across the heap. Walking the list means: load a node, read the next pointer, follow it to an address the prefetcher has no way to predict, wait, repeat.

Every element is a potential cache miss. Sixteen elements of a vector cost roughly one fetch. Sixteen elements of a list can cost sixteen.

So what about that O(n) insertion?

The shifting a vector does when you insert in the middle is std::memmove on a contiguous block. That is the single most optimised operation in computing: it runs in vectorised chunks, sixteen or thirty-two bytes per instruction, on data that is already being streamed into cache perfectly.

Moving a few thousand integers is a few microseconds. Finding the position to insert at in a linked list — which you must do first, and which the O(1) claim quietly excludes — means walking the list, one unpredictable fetch at a time.

The list's O(1) insert is real, but it is O(1) given an iterator you already hold. Getting that iterator is O(n) with a cache miss at every step. The vector's O(n) insert is O(n) in an operation that is roughly a hundred times cheaper per element.

A rough shape of what a benchmark shows, inserting into a sorted sequence of 10,000 ints, both built the same way, compiled with optimisations on:

std::vector    ~1.0x   (baseline)
std::list      ~8-15x slower

The exact numbers depend on your processor, your allocator and how fragmented the heap is. The direction does not change. Bjarne Stroustrup has been demonstrating this on stage for over a decade, and the first reaction in the room is always disbelief.

The numbers, concretely

It helps to see the hierarchy written down, because the ratios are not intuitive. Approximate latencies on a current desktop processor:

L1 cache          ~4 cycles        ~1 ns
L2 cache         ~12 cycles        ~4 ns
L3 cache         ~40 cycles       ~12 ns
main memory     ~200-300 cycles   ~70-100 ns

An L1 hit against a main-memory fetch is a factor of about seventy. If a vector walk hits L1 fifteen times out of sixteen and a list walk misses most of the time, that ratio is what you are trading away — and no amount of relinking pointers in constant time buys it back.

The other number worth internalising is the payload ratio. For std::list<int>, each 64-byte cache line you fetch contains two nodes, and of those 64 bytes, 8 are your integers. You are using 12% of the memory bandwidth you are paying for. For std::vector<int>, all 64 bytes are data: 100%.

Measuring it yourself

This is worth running rather than taking on trust, and it takes ten minutes. The shape of a fair test matters — benchmark the whole operation, including finding the insertion point, because that is what a program actually does:

#include <chrono>
#include <list>
#include <vector>
#include <algorithm>
#include <random>
#include <iostream>

template <typename Container>
long long timed_insert(int n)
{
    std::mt19937 rng{42};                      // same values for both
    std::uniform_int_distribution<int> dist{0, 1'000'000};

    Container c;
    const auto start = std::chrono::steady_clock::now();

    for (int i = 0; i < n; ++i) {
        const int value = dist(rng);

        // Find the position, then insert there. Both containers do
        // exactly this work; only the cost per step differs.
        auto pos = std::find_if(c.begin(), c.end(),
                                [value](int x) { return x > value; });
        c.insert(pos, value);
    }

    const auto end = std::chrono::steady_clock::now();
    return std::chrono::duration_cast<std::chrono::microseconds>(
               end - start).count();
}

int main()
{
    for (int n : {1'000, 10'000, 50'000}) {
        std::cout << n << " elements\n"
                  << "  vector " << timed_insert<std::vector<int>>(n) << " us\n"
                  << "  list   " << timed_insert<std::list<int>>(n)   << " us\n";
    }
}

Compile it with -O2 — without optimisations the measurement is meaningless, and this is the most common way benchmarks get reported wrongly. Run it a few times and take the lowest, to shed scheduling noise.

Two things will stand out. The vector wins at every size tested, and the gap grows rather than shrinking as n goes up — the opposite of what the complexity analysis predicts, because at larger sizes the list's nodes spread over more pages and the miss rate gets worse.

When the list does win

This is not "linked lists are useless". It is "the reason to choose one is not the complexity of insertion". A list earns its place when:

  • Elements are large and expensive to move. The vector's shift cost scales with sizeof(T) and with how expensive moving a T is. For big objects with non-trivial move constructors, the balance shifts.
  • You already hold iterators, and they must stay valid. This is the real reason to pick std::list. Inserting into a vector can reallocate, which invalidates every iterator, pointer and reference into it. A list's iterators survive any insertion or erasure except to the element they point at. If you are holding references across mutations, a list may be the only correct answer.
  • You splice. std::list::splice moves a range between lists in constant time, touching no elements. Nothing in a vector does that.
  • The sequence is genuinely huge and insertions are genuinely in the middle. At a hundred thousand elements and up, O(n) starts to dominate the constant factors.

That is a narrower set of conditions than most people assume when they reach for a list.

The rule that follows

The default sequence container in C++ is std::vector, and the bar for choosing something else is higher than the textbook implies. The C++ Core Guidelines say it outright: "Prefer using STL vector by default unless you have a reason to use a different container."

The same reasoning extends past these two types:

  • Prefer std::vector<T> to std::vector<T*> when you can. A vector of pointers is a contiguous array of addresses pointing at scattered objects — you have reintroduced exactly the problem.
  • std::unordered_map is a hash table whose buckets hold nodes, with the same scattering. For small maps, a sorted std::vector of pairs with a binary search frequently beats it.
  • Structure of arrays beats array of structures when you only touch some fields. If you iterate a million particles reading only their positions, storing positions in one contiguous array keeps every fetched cache line full of data you want, instead of filling it with velocity and colour you are about to skip.

Complexity analysis tells you how an algorithm scales. It deliberately discards constant factors, because the point is asymptotic behaviour. That is exactly the right abstraction when you are choosing between an O(n²) sort and an O(n log n) one, where no constant factor saves you.

It is the wrong tool for choosing between two O(n) walks where one of them is a hundred times slower per step. And "a hundred times" is not a constant factor you can wave away — it is the difference between a frame rendering and a frame dropping.

So: use big-O to rule out the algorithms that will not scale. Then measure the ones that survive, on your data, on your hardware, with optimisations on. Compiler Explorer will show you what your code becomes; a benchmark harness like Google Benchmark will tell you what it costs.

The same trap, one level up: array of structures

The bullet above about structure-of-arrays deserves a worked example, because it is where this idea pays the most and it has nothing to do with linked lists.

Say you are simulating particles. The obvious layout is a struct per particle, in a vector:

struct Particle {
    float x, y, z;          // position      12 bytes
    float vx, vy, vz;       // velocity      12 bytes
    float r, g, b, a;       // colour        16 bytes
    float mass, radius;     // physics        8 bytes
};                          //               48 bytes

std::vector<Particle> particles;        // array of structures

That reads beautifully and it is the right default. But now consider the render loop, which touches only the positions:

for (const auto& p : particles) {
    draw_point(p.x, p.y, p.z);          // 12 of the 48 bytes
}

Each 64-byte cache line holds one particle and a fragment of the next. You asked for 12 bytes of position and the hardware fetched 48 bytes of particle. Three quarters of your memory bandwidth went on velocity, colour and mass that this loop never reads.

The structure-of-arrays version splits the fields into parallel vectors:

struct ParticleSystem {
    std::vector<float> x, y, z;
    std::vector<float> vx, vy, vz;
    std::vector<float> r, g, b, a;
    std::vector<float> mass, radius;
};

Now the render loop walks three tight arrays of floats. A cache line of x holds sixteen x-coordinates, every one of which you want. The same loop moves a quarter of the memory and the prefetcher has three clean linear streams to follow instead of one strided one.

This is the layout games and physics engines use, and it is ugly — system.x[i] instead of particles[i].x, and nothing stops you desynchronising the vectors. Which is exactly why it is not the default. Write the readable version first, measure, and reach for this when the profiler says the loop is memory-bound. But know that it exists, because when it matters it is frequently a two-to-four times win on nothing but layout.

One more habit: reserve

While you are here, the cheapest performance win in C++ that nobody takes. A std::vector that grows past its capacity allocates a larger block, moves every element into it, and frees the old one. Growth is geometric — usually 1.5x or 2x — so appending n elements is amortised O(1), but it still means a handful of reallocations and a full copy of the data each time.

If you know roughly how many elements are coming, say so:

std::vector<Record> records;
records.reserve(expected_count);      // one allocation, not ~20

for (const auto& row : rows) {
    records.push_back(parse(row));
}

One line, one allocation instead of twenty, and every pointer and iterator stays valid throughout because nothing reallocates. For a loop that appends in bulk, this is routinely a measurable win for no loss of clarity.

The actual lesson, which is not about containers

The textbook was not lying to you. It was describing a machine where memory access was uniform, and you are not running on one.

c++ performance data structures cache stl vector