man erlang/sorting
How Erlang sorts: lists:sort, keysort and term order
lists:sort/1 takes a list of anything and needs no comparison function.
You can hand it atoms, tuples, maps and numbers in one list and it returns
them in a fixed order. Which order is that, what algorithm produces it, and
what does a comparison cost?
1> lists:sort([{2, x}, b, 3, {1, y}, a]).
[3,a,b,{1,y},{2,x}]
This article reads lists.erl and the comparison code of the runtime at the
tag OTP-29.1.3, the version Homebrew installs, and checks them with small
escripts run on an Apple M2 Pro. Every number below comes from that source,
the OTP documentation, or one of those runs.
The short version
Erlang defines a total order over all terms, so any two values can be
compared with < or =<. lists:sort/1 uses that order. It is a stable
merge sort written in Erlang. It first splits the list into runs that are
already ascending or descending, then merges them three lists at a time.
lists:sort/2 does the same with your fun, but merges two lists at a time.
lists:keysort/2 compares one element of each tuple and merges three at a
time like sort/1. A comparison of two small integers runs inline in the
JIT’s machine code. A comparison of two tuples calls a C function, and that
is why sorting tuples by plain term order is the slowest of the options
below.
The order between all terms
The reference manual lists the order between types:
number < atom < reference < fun < port < pid < tuple < map < nil < list < bit string
Tuples are ordered by size first, then element by element. Lists are
compared element by element. Atoms compare by their text. An integer and a
float compare by value, so 1 == 1.0 is true (=:= tells them apart).
Here is a script that sorts one of each, plus a few tuples and two equal numbers:
#!/usr/bin/env escript
-record #point{x, y}.
main(_) ->
Mixed = [<<"bin">>, [1], [], #{a => 1}, #point{x = 1, y = 2}, {1, 2},
self(), fun main/1, make_ref(), atom, 2.5, 1],
io:format("~p~n", [lists:sort(Mixed)]),
io:format("~p~n", [lists:sort([{2, x}, {9}, {1, y, z}, {1, b}, {1, a}])]),
io:format("~p ~p~n", [lists:sort([1.0, 1]), lists:sort([1, 1.0])]).
$ escript order.erl
[1,2.5,atom,#Ref<0.3077068277.261881860.174205>,
#Fun<order_erl__escript__1796__218365__81481__2245.0.76778702>,<0.10.0>,
{1,2},
#order_erl__escript__1796__218365__81481__2245:point{x = 1,y = 2},
#{a => 1},
[],
[1],
<<"bin">>]
[{9},{1,a},{1,b},{2,x},{1,y,z}]
[1.0,1] [1,1.0]
Three things show up. {9} comes before {1, a} because a 1-tuple is
smaller than any 2-tuple, whatever it holds. 1.0 and 1 compare equal,
so a stable sort leaves them in the order it got them. And #point{} sits
between the tuple and the map, although the documented order has no place
for it. It is a native record, a type that is new in OTP 29 and marked
experimental. The runtime’s header file has the full order in a comment,
“number < atom < ref < fun < port < pid < tuple < record < map < nil < cons
< binary”, and assigns each type a tag number that fits it.
That order is what makes this idiom work:
Counts = [{apple, 3}, {fig, 7}, {kiwi, 3}],
lists:reverse(lists:sort([{N, Word} || {Word, N} <- Counts])).
%% [{7,fig},{3,kiwi},{3,apple}]
Put the count first and the tuples sort by count, and on equal counts by the word. No fun is needed. Whether it is fast is another matter; see below.
lists:sort/1 is Erlang code
There is no C sort behind lists:sort/1. The function is in lists.erl,
and its first job is to look at the first two elements. If they are in
order, it calls split_1, which walks the list collecting an ascending run:
split_1(X, Y, [Z | L], R, Rs) when Z >= Y ->
split_1(Y, Z, L, [X | R], Rs);
split_1(X, Y, [Z | L], R, Rs) when Z >= X ->
split_1(Z, Y, L, [X | R], Rs);
split_1(X, Y, [Z | L], [], Rs) ->
split_1(X, Y, L, [Z], Rs);
split_1(X, Y, [Z | L], R, Rs) ->
split_1_1(X, Y, L, R, Rs, Z);
split_1(X, Y, [], R, Rs) ->
rmergel([[Y, X | R] | Rs], []).
X and Y are the two largest elements of the current run, and R holds
the rest of the run in reverse. An element at least as large as Y extends
the run. One that falls between X and Y is slotted in between them.
Anything smaller goes to the bottom while the run has only two elements, and
is otherwise held aside. If the next element doesn’t fit the run either, the
run is pushed onto Rs and a new one starts from the held element and that
one. If the first two elements were out of order, split_2 does the same
for a descending run. Its tests are strict (>), so a descending run never
holds two equal elements, which reversing it later would swap.
When the list is used up, mergel and rmergel merge the runs. They take
three runs at a time (merge3_1), and they alternate between producing
ascending and descending output. Merging two descending lists from the front
builds an ascending result in reverse, so by switching direction on each
pass most merges need no lists:reverse. Only a run left over at the end of
a pass gets reversed.
Counting comparisons
lists:sort/2 runs the same split-then-merge plan with your fun, so
counting calls to the fun shows the plan at work. This escript counts with a
counters array:
#!/usr/bin/env escript
main(_) ->
N = 10000,
rand:seed(exsss, {1, 2, 3}),
Shuffled = [X || {_, X} <- lists:sort([{rand:uniform(), X} || X <- lists:seq(1, N)])],
Runs = lists:append([lists:seq(I + 999, I, -1) || I <- lists:seq(1, N, 1000)]),
Inputs = [{sorted, lists:seq(1, N)},
{reversed, lists:seq(N, 1, -1)},
{ten_runs, Runs},
{shuffled, Shuffled}],
[io:format("~-9s ~6w calls~n", [Name, calls(L)]) || {Name, L} <- Inputs],
io:format("n log2 n: ~w~n", [round(N * math:log2(N))]).
calls(List) ->
C = counters:new(1, []),
lists:sort(fun(A, B) -> counters:add(C, 1, 1), A =< B end, List),
counters:get(C, 1).
$ escript calls.erl
sorted 9999 calls
reversed 9999 calls
ten_runs 29026 calls
shuffled 128496 calls
n log2 n: 132877
A sorted list and a reversed one each cost n − 1 comparisons. Each is one run, with nothing to merge. Ten descending runs of 1,000 numbers cost 29,026, a fraction of the shuffled case. The shuffled list needs 128,496 calls, just under n log₂ n.
The fun is a less-than-or-equal
The documentation asks for a fun that returns true when A compares less
than or equal to B. That is what keeps lists:sort/2 stable. Write <
instead and equal elements come out reversed:
#!/usr/bin/env escript
main(_) ->
Words = [{pear, 2}, {fig, 1}, {plum, 2}, {kiwi, 1}],
io:format("=< ~p~n", [lists:sort(fun({_, A}, {_, B}) -> A =< B end, Words)]),
io:format("< ~p~n", [lists:sort(fun({_, A}, {_, B}) -> A < B end, Words)]),
io:format("keysort ~p~n", [lists:keysort(2, Words)]).
$ escript ties.erl
=< [{fig,1},{kiwi,1},{pear,2},{plum,2}]
< [{kiwi,1},{fig,1},{plum,2},{pear,2}]
keysort [{fig,1},{kiwi,1},{pear,2},{plum,2}]
For a descending sort, >= is the right fun for the same reason. It
returns true when A goes first or the two are equal.
What a comparison costs
sort/1, sort/2 and keysort/2 look like three ways to say the same
thing. They are not equally fast. This script sorts 50,000 shuffled integers
and the same numbers as 2-tuples {X, X}, and keeps the best of 21 runs of
each:
#!/usr/bin/env escript
main(_) ->
rand:seed(exsss, {1, 2, 3}),
Ints = [X || {_, X} <- lists:sort([{rand:uniform(), X} || X <- lists:seq(1, 50000)])],
Pairs = [{X, X} || X <- Ints],
Cases = [{"integers, sort/1", fun() -> lists:sort(Ints) end},
{"integers, sort/2 with =<", fun() -> lists:sort(fun(A, B) -> A =< B end, Ints) end},
{"pairs, sort/1", fun() -> lists:sort(Pairs) end},
{"pairs, sort/2 on first", fun() -> lists:sort(fun({A, _}, {B, _}) -> A =< B end, Pairs) end},
{"pairs, keysort(1)", fun() -> lists:keysort(1, Pairs) end}],
[io:format("~-26s ~5.2f ms~n", [Name, best(F) / 1000]) || {Name, F} <- Cases].
best(F) -> lists:min([element(1, timer:tc(F)) || _ <- lists:seq(1, 21)]).
$ escript cost.erl
integers, sort/1 3.66 ms
integers, sort/2 with =< 5.81 ms
pairs, sort/1 9.78 ms
pairs, sort/2 on first 7.04 ms
pairs, keysort(1) 4.84 ms
sort/2 with a fun took 5.81 ms on the integers, against 3.66 ms for
sort/1. That gap mixes two things, the call of the fun and the two-way
merges of sort/2, so I don’t read it as the price of a fun. The tuple rows
are cleaner. Plain sort/1 on the pairs takes 9.78 ms, 2.7 times as long
as on integers, and more than sort/2 with a fun that pulls out the first
element and compares that. keysort(1) merges three lists at a time like
sort/1 and does the same work on the same pairs in 4.84 ms. The difference
between those two is what comparing whole tuples costs.
The reason is in the JIT. For X =< Y, the ARM64 code generator in
instr_common.cpp checks whether both operands are small integers and, if
so, compares them inline, without leaving the generated code. Anything else
goes to a shared fragment. It compares two floats itself, sends two atoms to
erts_cmp_atoms, and everything else to erts_cmp_compound in utils.c,
the generic C comparison that walks both terms. Every tuple comparison pays for that call, while the fun’s
A =< B on the extracted integers stays in machine code.
keysort avoids both costs. It takes element(I, X) out of each tuple and
compares the keys with =< in its own guards, so small-integer keys get the
inline test and no fun is called. Here it sorts the pairs in 4.84 ms,
between plain integers and the fun.
Ties make the difference larger. With counts from 1 to 10 for 50,000 keys,
sorting {Count, Key} by term order has to compare the keys too whenever
the counts are equal, while a fun or keysort on the count stops there.
#!/usr/bin/env escript
%% 50,000 {Key, Count} pairs whose counts are 1..10, so most counts tie.
main(_) ->
rand:seed(exsss, {4, 5, 6}),
Pairs = [{K, rand:uniform(10)} || K <- lists:seq(1, 50000)],
Swapped = [{C, K} || {K, C} <- Pairs],
Cases = [{"sort/2, fun on count", fun() -> lists:sort(fun({_, A}, {_, B}) -> A =< B end, Pairs) end},
{"sort/1 on {Count, Key}", fun() -> lists:sort(Swapped) end},
{"keysort(2)", fun() -> lists:keysort(2, Pairs) end}],
[io:format("~-24s ~5.2f ms~n", [Name, best(F) / 1000]) || {Name, F} <- Cases].
best(F) -> lists:min([element(1, timer:tc(F)) || _ <- lists:seq(1, 21)]).
$ escript ties_cost.erl
sort/2, fun on count 5.61 ms
sort/1 on {Count, Key} 8.79 ms
keysort(2) 3.71 ms
So the {Count, Key} idiom from above is the shortest code and the slowest
sort. lists:keysort(2, Pairs) followed by lists:reverse gives the same
descending order of counts, and on equal counts keeps the reverse of the
input order instead of ordering by key.
Curious facts
- A native record (OTP 29) sorts after every tuple and before every map.
The comment in
erl_term.hsays so, the reference manual’s list of the order doesn’t include it, and the experiment above confirms it. lists:sort([1.0, 1])returns[1.0, 1]andlists:sort([1, 1.0])returns[1, 1.0]. The two numbers compare equal, and the sort is stable. Thelists:sort/1documentation uses this exact example.- In map key order, as opposed to term order, integers are less than floats: the reference manual says so when it describes how two maps compare.
- Since every atom sorts after every number, a tuple like
{infinity, none}is larger than any tuple of two numbers and makes a handy starting value when you search for a minimum. - A sorted or reverse-sorted list costs
lists:sort/2exactly n − 1 calls of the fun.
History
- OTP 24.0 (ERTS 12.0) added BeamAsm, the JIT that inlines small-integer
comparisons, on x86-64. OTP 25.0 (ERTS 13.0): “The JIT now works for
64-bit ARM processors.”
erlang:system_info(emu_flavor)printsjiton the M2 Pro used here. - OTP 28.0.2 (STDLIB 7.0.2) fixed “a set of small bugs in sort
stability” for
lists:sort/1andlists:keysort. The release note says that forsort/1the bug could only be seen with integers and floats of equal value, and forkeysortonly when the list started with two tuples whose keys compared equal. - OTP 29 introduced native records, the one type missing from the documented term order.
Sources
lib/stdlib/src/lists.erlat OTP-29.1.3:sort/1,keysort/2,sort/2,split_1,split_2,mergel,rmergel,keymergel,fsplit_1andfmergel, ordering function contracterts/emulator/beam/erl_term.h, term order comment and tagserts/emulator/beam/jit/arm/instr_common.cpp,emit_arith_compare_sharedandemit_is_lterts/emulator/beam/utils.c,erts_cmp_compound- Reference manual, Term Comparisons
- Reference manual, Native Records
- STDLIB release notes, 7.0.2
- ERTS release notes: 12.0 (BeamAsm), 13.0 (64-bit ARM)
otp_versions.table, for which OTP release shipped STDLIB 7.0.2, ERTS 12.0 and ERTS 13.0
grep -rl /lib/erlang/sorting/
ls erlang/
- draft ETS: mutable tables in an immutable languageHow ETS gives Erlang a mutable hash table in Erlang/OTP 29: who owns a table, how update_counter changes a number in place, the linear hash table behind a set, the copies on every read, and what it costs against a map.
- draft Maps on the BEAM: flatmaps, HAMTs and immutabilityWhat an Elixir map is inside Erlang/OTP 29: a sorted key tuple and a value array up to 32 keys, a 16-way hash trie after that, and how an immutable update gets away with copying a few dozen words.