man ocaml/compare
OCaml's polymorphic compare: convenient and slow
OCaml has one function that can order two ints, two strings, two lists of
records or two trees, with no type class and no Ord instance:
val compare : 'a -> 'a -> int
How can a function with that type know how to compare anything, and what does
that cost? The answer is that it doesn’t look at types at all. It walks the
two values’ memory representation in C. This article reads runtime/compare.c
and the compiler’s lambda/translprim.ml at OCaml 5.5.2 and measures the
result with programs compiled by ocamlopt 5.5.2 (no flambda) on an Apple M2
Pro.
The short version
compare, =, <>, <, <=, > and >= are all one C function,
do_compare_val, which walks two values side by side with an explicit stack.
Immediate values (ints, chars, constant constructors) compare as integers;
blocks compare by tag, then size, then field by field from the left; strings
compare with memcmp. When the compiler knows at the call site that the type
is int, char, float, string, bytes, int32, int64 or nativeint,
it replaces the call with a specialised comparison and the C function never
runs. When it doesn’t know, every comparison is a call into the runtime. In my
measurements that costs about 2.5 times a typed int comparison, and 4.4 times
for a pair of ints.
What the runtime does
All seven operators end in compare_val
(compare.c L337-L382).
They differ only in the total flag. compare passes 1, and the boolean
operators pass 0. The loop itself
(L130-L335)
goes roughly like this:
loop:
if total and v1 is v2 (same pointer) -> equal, next item
v1, v2 both ints -> return v1 - v2
one int, one block -> the int is smaller
tags differ -> return tag1 - tag2
String_tag -> memcmp on the common prefix, then lengths
Double_tag -> float comparison, NaN rules (below)
closures -> raise Invalid_argument "compare: functional value"
any other block:
sizes differ -> return size1 - size2
push (v1, v2, next field = 1) on the stack
continue with field 0 of each
next item:
stack empty -> equal; else pop and compare the next field
The stack is a C array that starts with 8 entries on the C stack, moves to
the heap at 32 and doubles from there. A doubling that would reach 1,048,576
entries (COMPARE_STACK_MAX_SIZE) is refused, so at 524,288 pending items the
comparison gives up with Out_of_memory
(L30-L83).
Every 1024 iterations it checks for pending signals and GC work, so a very
long comparison still lets other things happen
(L40,
L323-L332).
Because the runtime only sees memory, the order it gives is a property of the representation. A few results from a test program:
compare (Circle 1) Empty 1
compare {b=1;a=2} {b=2;a=1} -1
compare "b" "ab" 1
compare [1;2;3] [2] -1
compare [|1;2;3|] [|2|] 1
- In
type shape = Circle of int | Empty,Emptyis declared second but has no argument, so it is stored as the immediate 0, and an immediate is smaller than any block. Constant constructors sort before all non-constant ones, whatever the declaration order. - Records compare field by field in declaration order, so the record type
{ b : int; a : int }sorts bybfirst. - Lists compare lexicographically, because a list is a chain of two-field blocks and the head is field 0.
- Arrays compare by length first.
[|1;2;3|]is greater than[|2|]because the sizes differ, before any element is looked at.
NaN, and the physical-equality shortcut
The total flag changes two things. For floats, compare treats NaN as equal
to itself and smaller than every other float, while the boolean operators
follow IEEE and call NaN unordered
(L224-L238):
nan = nan false
compare nan nan 0
compare nan neg_infinity -1
nan < neg_infinity false
List.sort compare [3.; nan; 1.] nan; 1.; 3.
And only compare takes the shortcut on line 141: if the two values are the
same pointer, they are equal, without looking inside. = can’t take it,
because a NaN inside a structure would make the structure unequal to itself.
That gives two odd results:
let f = fun x -> x + 1
compare f f (* 0 *)
f = f (* Invalid_argument "compare: functional value" *)
let rec cyc = 1 :: cyc
compare cyc cyc (* 0 *)
cyc = cyc (* never returns *)
I ran the last line under timeout 3; it was killed after three seconds with
exit status 124.
When the compiler steps in
compare is declared in stdlib.ml as external compare : 'a -> 'a -> int = "%compare", a primitive the compiler handles itself, and it looks at the
type at every use. specialize_primitive in
translprim.ml L520-L545
checks the type of the first argument. If it is int or char, or any type
whose values are always immediate, the comparison becomes Compare_ints. If
it is float, string, bytes, nativeint, int32 or int64, it becomes
the matching specialised comparison. Anything else stays generic, and
ocamlopt -dlambda shows which one you got:
let cmp_poly a b = compare a b (* 'a -> 'a -> int *)
let cmp_int (a : int) b = compare a b
let eq_pair (a : int * int) b = a = b
let is_empty l = l = []
$ ocamlopt -dlambda -c spec.ml
(seq
(let
(cmp_poly/274 = (function a/276 b/277 : int (caml_compare a/276 b/277)))
(setfield_ptr(root-init) 0 (global Spec!) cmp_poly/274))
(let
(cmp_int/278 =
(function a/280[int] b/281[int] : int (compare_ints a/280 b/281)))
(setfield_ptr(root-init) 1 (global Spec!) cmp_int/278))
(let (eq_pair/282 = (function a/284 b/285 : int (caml_equal a/284 b/285)))
(setfield_ptr(root-init) 2 (global Spec!) eq_pair/282))
(let (is_empty/286 = (function l/288 : int (== l/288 0)))
(setfield_ptr(root-init) 3 (global Spec!) is_empty/286))
0)
The last one is the has_constant_constructor case. = or <> against a
constant constructor like [] or None becomes a single integer test,
because the constant is an immediate and anything else is a block.
Specialisation also happens when compare is passed as a value. In
List.sort compare ints with ints : int list, -dlambda shows the
eta-expanded function containing compare_ints. This means the usual advice
to “write Int.compare instead of compare” doesn’t change the code for
ints: stdlib/int.ml defines let compare : int -> int -> int = Stdlib.compare
(L40), which is
the same specialisation by type annotation.
What specialisation can’t see through is a function boundary. cmp_poly was
compiled once, for all types, so it calls caml_compare even when you pass it
ints. A comparison on a tuple, a record, a list or an option is always
generic, since none of those is on the list.
What it costs
A loop of 100 million calls, each through a function marked
[@inline never] so the call overhead is the same, best of 3 with
Sys.time:
ints, specialised 2.22 ns/call
ints, polymorphic 5.69 ns/call
pairs, polymorphic 10.11 ns/call
pairs, field-wise Int.compare 2.29 ns/call
strings, typed (caml_string_compare) 5.93 ns/call
strings, polymorphic 10.64 ns/call
Those times include the loop and the call. The generic path costs about 3.5
ns more per int comparison and 7.8 ns more per pair. A string comparison is a
C call either way (translprim.ml maps it to caml_string_compare), so typing it saves only the generic
dispatch.
In a sort, the comparison is one cost among several. Sorting the same 1,000,000 random ints, best of 5:
List.sort compare (int list) 322.2 ms
List.sort Int.compare 323.0 ms
List.sort cmp_int (annotated, not inlined) 319.4 ms
List.sort cmp_poly (polymorphic helper) 369.4 ms
Array.sort compare (copy + sort) 207.0 ms
Array.sort cmp_poly (copy + sort) 270.1 ms
Array.stable_sort compare (copy + sort) 160.0 ms
List.sort compare (int * int pairs) 547.7 ms
List.sort field-wise Int.compare (pairs) 421.6 ms
compare, Int.compare and the annotated helper are the same code and the
same time. The polymorphic helper adds 15% to List.sort and 30% to
Array.sort. On pairs, a hand-written comparison that matches on the first
Int.compare and falls through to the second saves 23%.
Curious facts
List.sort,List.stable_sortandList.fast_sortare one function:let sort = stable_sortandlet fast_sort = stable_sort(list.ml L452-L453).Array.sortis a heap sort where every node has three children (i+i+i+1is the first child ofi), and it is not stable (array.ml L353-L400). In the benchmark above it is slower thanArray.stable_sort, a merge sort.array.mlialso saysstable_sort“is usually faster than the current implementation of sort”.- A generic
Hashtblfinds keys withcompare k key = 0, not=, so anankey can be looked up again. - Comparing two custom blocks of different kinds, say an
Int64against aBigarray, is ordered bystrcmpon their type identifiers. The source calls this “hardening against comparisons between different types” (L273-L291).
History
- Objective Caml 3.00 (25 April 2000) added
List.sort,List.stable_sort,Array.sortandArray.stable_sort. - Objective Caml 3.01 (9 March 2001) reimplemented structural comparison “so as to avoid overflowing the C stack”.
- Objective Caml 3.08.0 (13 July 2004) gave NaN its current rules. The boolean
comparisons treat it as unordered,
compareas equal to itself and smaller than other floats. The entry adds thatx == yno longer impliesx = y, but still impliescompare x y = 0. - OCaml 4.08.0 (13 June 2019) added the
Intmodule, and with itInt.compareandInt.equal.
Sources
runtime/compare.cat 5.5.2: stack limits, do_compare_val, floats and NaN, custom blocks, blocks field by field, entry pointslambda/translprim.mlat 5.5.2: simplify_constant_constructor, specialize_primitive for comparisonsstdlib/int.mlL39-L40stdlib/list.mlL384-L453stdlib/array.mlL353-L400,stdlib/array.mliL348-L356stdlib/stdlib.mlL72Changesat 5.5.2: 3.08.0 NaN (L15314-L15319), 3.01 comparisons (L15969-L15970), 3.00 sorts (L16081, L16086), 4.08.0Int(L8400)- Stdlib in the OCaml manual
grep -rl /lib/ocaml/compare/
ls ocaml/
- draft How OCaml's Hashtbl and polymorphic hash workOCaml 5.5.2's Hashtbl is a bucket array of linked cells that doubles at load factor 2, hashed by a C function that stops after 10 values, with polymorphic compare for equality and randomization you have to ask for.