This is in fact what Base.Int.compare
(and therefore Core.Int.compare
) does (at least, in the latest GitHub version—I think the opam version is still using Poly.compare
). Apparently, it is about 20%-25% faster.
open! Core
open Core_bench.Std
let a = Sys.opaque_identity 0
let b = Sys.opaque_identity Int.min_value
let compare_int (a : int) b =
let int_of_bool (b : bool) = (Obj.magic b : int) in
int_of_bool (a > b) - int_of_bool (a < b)
;;
let () =
[ Bench.Test.create ~name:"Poly.compare" (fun () -> Poly.compare a b)
; Bench.Test.create ~name:"Int.compare" (fun () -> compare_int a b)
]
|> Bench.make_command
|> Command.run
;;
Output:
Estimated testing time 20s (2 benchmarks x 10s). Change using '-quota'.
┌──────────────┬──────────┬────────────┐
│ Name │ Time/Run │ Percentage │
├──────────────┼──────────┼────────────┤
│ Poly.compare │ 3.57ns │ 100.00% │
│ Int.compare │ 2.69ns │ 75.33% │
└──────────────┴──────────┴────────────┘