Choosing algorithms and data structures

Hand-drawn hatched terracotta trunk entering from the left and dividing into two thick and two thin channels over dense cream, linen, sand and umber cross-hatching with faint moss contours.

Choosing an algorithm or data structure means matching the operations a program needs and the inputs it will see to an implementation, then measuring it. Asymptotic complexity, the big-O bound on how work grows with input size, predicts how candidates scale. Measured speed also depends on constant factors, the memory hierarchy and setup costs (Chimani & Klein, 2010; LaMarca & Ladner, 1999; Liu & Vinter, 2015). Three questions remain open: whether cache-oblivious designs pay off, when a model can replace timing, and how well benchmarks measure the speed of generated code. The specific families have their own articles: sorting and searching, hash tables, search trees and ordered indexes, probabilistic data structures, graph algorithms, concurrent data structures, string algorithms and cache eviction.

Starting from the operations

A problem is defined by the operations it must support, and problems that look alike can call for different structures. Reference catalogues index problems by their input and desired result. Skiena’s repository sorts 75 problems into five groups and cross-links related formulations (Skiena, 1999). Introduction to Algorithms likewise treats single-source and all-pairs shortest paths as separate problems (Cormen et al., 2022).

Whether the data changes after the first query is a basic dividing line. Searching a fixed set permits simpler and more efficient solutions than a dictionary, a structure that keeps records keyed for lookup, insertion and deletion (Skiena, n.d.d; Skiena, n.d.a). In the same way, when no insertions happen after the first query, sorting once and scanning in order can replace a priority queue (Skiena, n.d.c). A request for the item at a given rank, such as the median, is a selection problem (Skiena, n.d.b; Cormen et al., 2022).

Setup cost belongs in the comparison when the program reuses a structure many times. Converting a sparse matrix to the CSR5 storage format can cost as little as a few matrix–vector multiplications, so its value depends on how many multiplications follow (Liu & Vinter, 2015). On a European road network, one preprocessing configuration gave faster route queries at twice the preprocessing time (Gottesbüren et al., 2019).

Why asymptotic complexity misleads

Algorithm engineering treats design, analysis, implementation and experiments as a cycle. Experimental results can change the design or lead to better guarantees for the inputs that occur (Sanders, 2009; Chimani & Klein, 2010). How running time scales depends on the structure of the input as well as its size, which makes scaling partly an empirical question (Johnson, 2001).

The memory hierarchy (the levels of cache between the processor and main memory) is a main reason why counting operations fails to rank algorithms. In one sorting comparison, a cache-tuned quicksort beat radix sort by 24% on the largest data set. It did so while executing more than three times as many instructions (LaMarca & Ladner, 1999).

Whether to avoid branches, the points where a program chooses between paths, depends on input size. For repeated searches in arrays small enough to fit in the fastest cache, branch-free versions of binary search sometimes ran twice as fast as branching versions (Khuong & Morin, 2015). On larger arrays, branching search stalled less, because the processor speculatively started later iterations before the keys arrived (Schulz et al., 2018).

Lower hardware counts do not guarantee less time. In one search study, branch-free binary searches had the fewest cache misses yet ran slowly on large arrays. Prefetching two keys per step caused more misses and made them faster (Schulz et al., 2018).

Vector instructions (SIMD, which apply one operation to several values at once) give gains that shrink or reverse with conditions. On an Intel Haswell processor, a wider SIMD mergesort was 42% faster than a narrower one with one thread, but only 14% faster with eight threads (Inoue, 2016). In a web server test, encryption using wider vector instructions raised throughput for static files but lowered it when the server also compressed files on the fly (Gottschlag & Bellosa, 2019).

Cache-oblivious and cache-conscious designs

Studies disagree on whether cache-oblivious algorithms, which are designed to use any cache well without knowing its size, beat code tuned for a specific cache. A tuned cache-oblivious sort, Lazy Funnelsort, could beat the best tested quicksort on inputs that fit in memory, but lost to a careful multiway mergesort on disk (Brodal et al., 2007). In dense linear algebra, highly optimized cache-oblivious programs were significantly slower than cache-conscious ones (Yotov et al., 2007).

Crossovers where simple methods win Strong evidence: many studies agree on this

Below some input size a method with a worse bound often wins, and the crossover point depends on the machine and the workload. In one experiment on a Xeon processor, binary search was slightly faster than linear scans up to 32 values and slower at 64 (Khuong, 2012). For arrays of six to 16 items, sorting networks beat insertion sort by at least 1.76 times. The gain was smaller once they served as the small-case sorter inside quicksort (Bingmann et al., 2020).

Asymptotically faster methods carry overheads that set a minimum useful size. On an NVIDIA V100 GPU, one level of Strassen’s matrix multiplication first beat NVIDIA’s cuBLAS library at size 1,536, by at most 1.11 times. A two-level version with extra workspace crossed over only at 7,680 (Huang et al., 2018b). A parallel in-place samplesort run on one thread was slower than BlockQuicksort on uniform inputs of at most 2¹⁵ items because of its initial overhead (Axtmann et al., 2017).

Memory layout shifts the crossover as well. Across machines, plain sorted order was the better layout for binary search on small arrays. On larger ones the Eytzinger layout usually won; it stores the implicit search tree level by level (Khuong & Morin, 2015). Cutoffs do not always travel between processors: explicit prefetching made array search much slower on some tested processors, particularly at small sizes (Khuong & Morin, 2015).

Predicting performance without timing

Analytic performance models, which predict speed from the hardware instead of timing the code, fit some computations closely and others poorly. The Execution-Cache-Memory model, which adds up in-core work and data transfers between cache levels, fit measured performance within 10% for one stencil computation across three memory-bound phases (Stengel et al., 2015). The simpler Roofline model could not tell apart the blocking strategies in the same example, and the authors report the Execution-Cache-Memory model to be overoptimistic for some tight loops (Stengel et al., 2015).

Extrapolating from small test cases is also risky. Small inputs can predict large-input running times poorly when cache behaviour changes with size (Landrum et al., 1998).

Standard-library defaults

Guarantees and implementations differ between libraries and releases. The JavaScript specification requires a stable sort, one that keeps equal keys in their original order, but leaves the algorithm to each engine (V8, 2019). The table lists what each library documents for its main sort or map.

LibraryOperationDocumented implementation
Rust standard librarystable and unstable slice sortdriftsort and ipnsort (The Rust Project Developers, n.d.c)
Java (Oracle JDK 25)Arrays.sort(int[])dual-pivot quicksort (Oracle, n.d.b)
CPython 3.14.0list sortadaptive merge sort with Powersort choosing which runs to merge (Python Software Foundation, 2025b)
V8 (2019)Array.prototype.sortTimsort (V8, 2019)
libc++ (LLVM 20.1.0)std::sortintrosort with insertion sort for small inputs, among other techniques (LLVM Project, n.d.c)
Go 1.24built-in mapSwiss Tables, a hash table design (Pratt, 2025)

Specialized algorithms can beat these defaults by large factors in narrow conditions. GCC’s library introsort was at least 1.86 times slower than a sequential in-place samplesort on 2³² uniformly distributed items (Axtmann et al., 2017). A vectorized quicksort was three to eight times faster than the standard library sort on one million random numbers on a single Apple M1 Max core (Blacher et al., 2022). Its integration into a parallel sorter gave a geometric mean speedup (an average suited to ratios) of 1.59 (Wassenberg et al., 2022).

Large gains in isolated operations shrink in whole programs. Go’s maintainers measured map operations up to 60% faster in Go 1.24 than in 1.23, with some regressions, but about a 1.5% improvement in CPU time across full application benchmarks (Pratt, 2025). V8’s switch to Timsort was up to 17 times faster on a constructed input of two reverse-sorted runs, yet left nearly all workloads of a web tooling benchmark about unchanged (Zünd, 2018).

Benchmarking that can be trusted

A benchmark is trustworthy when it reports enough about the algorithms, inputs, computing environment and results for readers to attempt a comparable experiment (Johnson, 2001). Many published comparisons fall short: in selected 2011 systems venues, 71 of the 90 papers that reported running times gave no measure of variation (Kalibera & Jones, 2013).

Measurements vary at several levels, such as between builds, between process runs and between iterations within a run. Kalibera and Jones recommend putting the repetitions where the uncertainty is greatest (Kalibera & Jones, 2013). Running each experiment in many randomized setups reduces bias from the conditions of one particular setup (Mytkowicz et al., 2009).

Warm-up cannot be assumed to end after a fixed number of iterations in runtimes that compile code while it runs. Depending on machine and operating system, only 30.0–43.5% of the virtual machine and benchmark pairs studied reached a steady state of peak performance (Barrett et al., 2017). Performance metrics covers the wider question of what to measure.

Speed of code written by language models

Code generated by language models can be slower than human solutions, and the evidence on how much of the gap comes from algorithm choice is thin. In the EffiBench benchmark, GPT-4 solutions that passed the tests took on average 3.12 times as long as the human reference solutions; failing outputs were not timed (Huang et al., 2024b). Timeouts in another benchmark, PROBE, included brute-force enumeration and repeating expensive operations after each update (Nogueira et al., 2026b).

On real repositories, agents asked to speed up code fall short of experts on average. In the SWE-fficiency benchmark, the top tested agents averaged less than 0.23 times the expert speedup (Ma et al., 2026f). The gap is not only a matter of choosing the wrong approach. On 66 tasks where no public patch reached reference speed, 32 best patches used the human reference’s broad optimization. That agreement alone did not explain the gap (Chen et al., 2026d).

Audits question how reliably these benchmarks measure speed. Re-run on other machines, the human reference patches passed the original validity rules every time on only 39 of 102 GSO tasks. The rate was 11 of 140 on SWE-Perf and 411 of 498 on SWE-fficiency (Chen et al., 2026d). Two benchmarks ranked the same eight submissions differently on nine of 28 pairs (Chen et al., 2026d). On tasks where the benchmark showed no significant timing difference, tests generated by two language models found significant improvements in 24.01% and 25.43% of them (Le et al., 2026).

The best of many attempts does much better than the average attempt. At least one of ten public submissions matched or beat the human reference on 384 of 450 tasks that replayed validly (Chen et al., 2026d).

In one study, feeding profiler measurements back to the agent after each patch improved its results. With GPT-5.1, it matched expert speed on 39.2% of GSO tasks against 19.6% for a standard agent, and on 74% against 26% on a smaller SWE-fficiency set (Deng et al., 2026). Its patches also passed GSO’s correctness tests more often, 96.1% against 88.2% (Deng et al., 2026). See AI coding agents for the wider evidence on such agents.

Further reading

  • Johnson (2001): a guide to designing, running and reporting experiments on algorithms, written for theorists.
  • Chimani and Klein (2010): an introduction to algorithm engineering and its cycle of design, analysis, implementation and experiments.
  • LaMarca and Ladner (1999): a sorting study showing that cache behaviour can reverse a ranking based on instruction counts.
  • Kalibera and Jones (2013): how to plan repetitions so that benchmark results carry an honest measure of uncertainty.
  • Skiena (1999): a catalogue that maps problems, by input and desired result, to algorithms and implementations.
  • Chen et al. (2026d): an audit of the benchmarks used to measure how well coding agents optimize code.

Known gaps

What this article cannot tell you yet.

  1. Automatic per-input algorithm selection and autotuning, and how much they gain over a fixed choice, were not researched.
  2. Most hardware measurements predate current multicore processors and current runtime versions; newer measurements of the same effects were not gathered.
  3. Independent tests of the standard-library implementations described here (Go maps, Rust, Java, CPython, V8 and libc++ sorts) beyond their maintainers’ own reports were not researched.
  4. Whether the coding-agent results transfer to other repositories and workload distributions was not researched, and the profiler-guided agent workflow rests on one preprint.
  5. The SWE-fficiency benchmark paper was available only as an abstract.
  6. Which hardware effect (memory, branches or vector instructions) matters most across problem families was not researched.

References

Solid source
Rated highly trustworthy by the research, and every passage taken from it was found in it.
Weak source
Rated low, or a passage taken from it was not found in it.
Medium trust
Rated medium by the research.
Not checked
Rated high, but its passages could not all be checked against it.
Show all 42 references