Skip to content

Instantly share code, notes, and snippets.

@mooreryan
Created February 17, 2022 18:06
Show Gist options
  • Save mooreryan/220b47feea6b253630dab09c4b6ed18c to your computer and use it in GitHub Desktop.
Save mooreryan/220b47feea6b253630dab09c4b6ed18c to your computer and use it in GitHub Desktop.
Benchmarking OCaml string splitting
open! Core
open! Core_bench
let s = "apple pie\tis really\tquite\ttasty and nice"
(* Like Core.String.split, but specialized for splitting on [char]. *)
let split str ~on =
let len = String.length str in
let rec loop acc last_pos pos =
if pos = -1 then String.sub str ~pos:0 ~len:last_pos :: acc
else if Char.equal str.[pos] on then
let pos1 = pos + 1 in
let sub_str = String.sub str ~pos:pos1 ~len:(last_pos - pos1) in
loop (sub_str :: acc) pos (pos - 1)
else loop acc last_pos (pos - 1)
in
loop [] len (len - 1)
let () =
let bench name f = Bench.Test.create ~name (fun () -> f ()) in
Command.run
(Bench.make_command
[
bench "String.split" (fun () -> String.split s ~on:'\t');
bench "split" (fun () -> split s ~on:'\t');
bench "Caml.String.split_on_char" (fun () ->
Caml.String.split_on_char '\t' s);
])
(executable
(name bench)
(libraries core core_bench))
(lang dune 2.9)

Run the benchmark

$ dune exec ./bench.exe
Estimated testing time 30s (3 benchmarks x 10s). Change using '-quota'.

┌───────────────────────────┬──────────┬─────────┬────────────┐
│ Name                      │ Time/Run │ mWd/Run │ Percentage │
├───────────────────────────┼──────────┼─────────┼────────────┤
│ String.split              │ 222.19ns │  33.00w │    100.00% │
│ split                     │ 106.01ns │  29.00w │     47.71% │
│ Caml.String.split_on_char │  74.38ns │  23.00w │     33.47% │
└───────────────────────────┴──────────┴─────────┴────────────┘
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment