title: Ocaml performance vs go
body: <p>I'm trying to implement utf8 decoding in Ocaml as a learning project. To check the performance I'm benchmarking against the go standard library.</p>
  
  <p>This is the go code:</p>
  
  <pre><code>package main
  
  import (
      "fmt"
      "time"
      "unicode/utf8"
  )
  
  func main() {
      start := time.Now()
  
      for i := 0; i &lt; 1000000000; i++ {
          utf8.ValidRune(23450)
      }
  
      elapsed := time.Since(start)
      fmt.Println(elapsed)
  }
  </code></pre>
  
  <p>When I run it, I get:</p>
  
  <pre><code>go build b.go
  ./b
  344.979492ms
  </code></pre>
  
  <p>I decided to write an equivalent in ocaml:</p>
  
  <pre><code>let min = 0x0000
  let max = 0x10FFFF
  
  let surrogateMin = 0xD800
  let surrogateMax = 0xDFFF
  
  let validUchar c =
    if (0 &lt;= c &amp;&amp; c &lt; surrogateMin) then
      true
    else if (surrogateMax &lt; c &amp;&amp; c &lt;= max) then
      true
    else
      false
  
  let time f x =
      let t = Sys.time () in
      let _ = f x in
      let t2 = Sys.time () in
      let diff = (t2 -. t) *. 1000. in
      print_endline ((string_of_float diff) ^ "ms")
  
  
  let test () =
    for i = 0 to 1000000000 do
      let _ = validUchar 23450 in
      ()
    done
  
  let () = time test ()
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>ocamlopt bMl.ml -o bMl
  ./bMl
  2041.075ms
  </code></pre>
  
  <p>The ocaml equivalent basically copies the implementation of the go stdlib from <a href="https://golang.org/src/unicode/utf8/utf8.go#L517" rel="nofollow noreferrer">https://golang.org/src/unicode/utf8/utf8.go#L517</a></p>
  
  <p>Why is the ocaml code so much slower? </p>