man javascript/array-sort

How V8 sorts arrays: TimSort in Torque

lib / JavaScript 8 mindraft

checked against: V8 12.9.202.28 (Node 23.11.0)

Every JavaScript programmer meets this once:

[10, 9, 1, 100].sort()                  // [1, 10, 100, 9]
[10, 9, 1, 100].sort((a, b) => a - b)   // [1, 9, 10, 100]

The first result is what the specification asks for. This article follows Array.prototype.sort from the spec into V8 12.9.202.28, the engine in Node 23.11.0, to see what actually runs. Node ships that V8 as 12.9.202.28-node.14; the files cited here are byte-identical in Node’s deps/v8 at v23.11.0.

What the spec asks for

Array.prototype.sort (section 23.1.3.30) reads the elements into a list, sorts the list with SortIndexedProperties, writes it back, and deletes the leftover indices. Three rules matter in practice.

The default comparison is on strings. CompareArrayElements (23.1.3.30.2) puts undefined after everything else. With no comparator it then converts both values with ToString and compares the strings. "100" comes before "9" because "1" comes before "9".

A comparator’s result goes through ToNumber, and NaN counts as 0. A comparator returning true or false therefore returns 1 or 0, never a negative number.

The sort is stable. SortIndexedProperties lists conditions on the permutation, ending with: if two elements compare equal, the one that came first stays first, “i.e., the sort is stable”. If the comparator isn’t “consistent”, the order is implementation-defined. Consistency includes returning the same Number for the same pair, symmetry of “equal”, and transitivity.

Step 1: the default comparison, without strings

V8’s version of CompareArrayElements without a comparator is SortCompareDefault in third_party/v8/builtins/array-sort.tq. Its first lines skip the strings entirely when both values are small integers (Smis):

if (TaggedIsSmi(x) && TaggedIsSmi(y)) {
  return SmiLexicographicCompare(UnsafeCast<Smi>(x), UnsafeCast<Smi>(y));
}

SmiLexicographicCompare calls the C++ function Smi::LexicographicCompare in src/objects/objects.cc. It answers “which decimal string is smaller” with arithmetic:

  • equal values are equal strings;
  • if either value is 0, numeric order is string order;
  • a negative number sorts before a positive one, because '-' is below every digit; two negatives are compared by their absolute values;
  • otherwise it counts the digits of each number with a bit trick ((log2 + 1) * 1233 >> 12, then a correction against a table of powers of 10), scales the shorter one up by a power of 10 so both have the same number of digits, and compares. If the scaled values are equal, the shorter number comes first, because a prefix sorts before a longer string.

The result is the same as converting to strings:

$ node -e 'console.log([-1, -10, 2, 0].sort())'
[ -1, -10, 0, 2 ]

-1 comes before -10 because "-1" is a prefix of "-10".

Step 2: set aside holes and undefined

Before sorting, CompactReceiverElementsIntoWorkArray copies the elements into a separate FixedArray, the work array. It skips holes and only counts undefined values. So the comparator never sees either. After the sort, CopyWorkArrayToReceiver writes back the sorted values, then the counted undefineds, then deletes indices up to the old length, which recreates the holes at the end.

console.log([3, undefined, 1, , 2].sort());
console.log([3, undefined, 1, , 2].toSorted());
const seen = [];
[3, undefined, 1, , 2].sort((a, b) => { seen.push(a, b); return a - b; });
console.log("comparator saw undefined:", seen.includes(undefined));
$ node holes.mjs
[ 1, 2, 3, undefined, <1 empty item> ]
[ 1, 2, 3, undefined, undefined ]
comparator saw undefined: false

toSorted runs the same code with isToSorted set, which counts a hole as an undefined, so the copy has no holes left.

Elements are loaded through a function pointer chosen by the array’s elements kind (Load<FastSmiElements>, Load<FastDoubleElements>, Load<FastObjectElements> or a generic accessor). A comparator can change the array while the sort runs. After sorting, ArrayTimSort checks that the array’s map and length are unchanged, and if not it writes back through the generic, spec-following accessors.

Step 3: TimSort

The file starts with the Python Software Foundation’s copyright, years 2001 to 2018, and says it implements TimSort “based on” CPython’s listobject.c, with listsort.txt as the description. The main loop, ArrayTimSortImpl, is CPython’s algorithm in Torque, V8’s TypeScript-like language for writing builtins.

Minimum run length. ComputeMinRunLength returns n itself below 64. Otherwise it shifts n right until it is below 64 and adds 1 if any shifted-out bit was set, giving a value between 32 and 64. I ran the same arithmetic for a few sizes, in a JavaScript copy of the function (minrun.mjs):

$ node minrun.mjs
n=63 minrun=63
n=64 minrun=32
n=65 minrun=33
n=1000 minrun=63
n=100000 minrun=49

Runs. CountAndMakeRun reads elements while they keep going up (a[i] <= a[i + 1]) or keep going strictly down (a[i] > a[i + 1]). A descending run is reversed in place. It has to be strictly descending, because reversing equal elements would swap them and break stability.

Short runs. A run shorter than minrun is extended to minrun elements with BinaryInsertionSort. It finds each insertion point with a binary search and then shifts elements to make room. The comment explains the choice: few comparisons, at the cost of moving data, “an advantage since comparisons are more expensive due to calling into JS”. An array of fewer than 64 elements is one binary insertion sort and nothing else.

Merging. Each run is pushed on a stack of pending runs, and MergeCollapse merges neighbours until two invariants hold:

1. run_length(i - 3) > run_length(i - 2) + run_length(i - 1)
2. run_length(i - 2) > run_length(i - 1)

CPython’s merge_collapse checked the same two rules up to 3.10 and switched to the “powersort” merge policy in 3.11. V8 12.9 still uses them. The stack has room for kMaxMergePending = 85 runs, which the comment says is enough for an array of 2⁶⁴ elements.

Galloping. GallopLeft and GallopRight find where a key belongs in a run by probing at offsets 1, 3, 7, 15 and so on (offset = (offset << 1) + 1), then finishing with a binary search between the last two probes. MergeAt uses them first to skip the part of each run that is already in place. It copies the shorter of the two remaining runs into a temporary array and calls MergeLow or MergeHigh. Those merge one element at a time until one side has won minGallop times in a row, starting at kMinGallopWins = 7, and then call the gallop functions to move a whole block from the winning side at once. Each time galloping pays off, minGallop drops by one; leaving galloping mode raises it again.

What it costs, in comparisons

I counted comparator calls on arrays of numbers: pseudo-random ones from a linear congruential generator, and the integers 0 to n − 1 in both orders.

function count(arr, cmp = (a, b) => a - b) {
  let n = 0;
  arr.sort((a, b) => { n++; return cmp(a, b); });
  return n;
}
let seed = 1;
const rand = () => (seed = (seed * 1103515245 + 12345) % 2147483648);
for (const n of [10, 64, 1000, 100000]) {
  const random = Array.from({ length: n }, rand);
  const asc = Array.from({ length: n }, (_, i) => i);
  const desc = asc.toReversed();
  console.log(`n=${n}: random ${count(random)}, ascending ${count(asc)}, descending ${count(desc)}, n*log2(n) ${Math.round(n * Math.log2(n))}`);
}
$ node sortcount.mjs
n=10: random 22, ascending 9, descending 9, n*log2(n) 33
n=64: random 304, ascending 63, descending 63, n*log2(n) 384
n=1000: random 8649, ascending 999, descending 999, n*log2(n) 9966
n=100000: random 1529289, ascending 99999, descending 99999, n*log2(n) 1660964

Sorted input in either direction is one run: n − 1 comparisons and, for the descending case, one reversal. Random input stays a little under n log₂ n.

A comparator that returns a boolean

(a, b) => a > b looks like it should work. It returns true or false, which become 1 or 0, so it never says “less than”. For a < b it calls the pair equal one way round (a > b is 0) and not the other (b > a is 1), which breaks the symmetry rule, so the spec leaves the result to the engine. In V8 the very first comparison in CountAndMakeRun decides the direction, and 0 or 1 never reads as descending, so a descending array is one long “ascending” run:

$ node -e 'const a = Array.from({ length: 20 }, (_, i) => 20 - i); console.log(a.toSorted((x, y) => x > y).join(" "))'
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Nothing moves.

Curious facts

  • V8’s sort file carries Python’s copyright line, because it is a port of CPython’s C code.
  • [1, 2, 3].sort(() => NaN) returns [1, 2, 3]. NaN becomes 0, every pair is “equal”, and a stable sort keeps them in place.
  • The default sort of small integers never builds a string; it counts decimal digits with * 1233 >> 12.
  • Holes don’t survive toSorted: they come back as undefined, while sort keeps them as holes at the end.
  • A 63-element array never merges anything. It is sorted entirely by binary insertion.

History

  • V8 6.9 (tag 6.9.427.1): sort is JavaScript in src/js/array.js, a QuickSort that switches to insertion sort when a range has 10 or fewer elements. src/builtins/array-sort.tq is an empty placeholder with the comment “TimSort implementation will go here”.
  • V8 7.0 (tag 7.0.276.1): ArrayPrototypeSort is a Torque builtin in third_party/v8/builtins/array-sort.tq, a TimSort, and bootstrapper.cc installs it as Array.prototype.sort. The V8 blog announced it on 28 September 2018 for V8 7.0 and Chrome 70.
  • ES2019: the spec changes “The sort is not necessarily stable” to “The sort must be stable”.
  • ES2023: Array.prototype.toSorted.

Sources

ls javascript/