Hacker News new | ask | show | jobs
by mas644 5389 days ago
You know how it is with benchmarks...it can vary so much. I'm not sure how much work is done these days on the OCaml compiler. I recall there being a big debate a few years back about it, a lot of people cried foul that OCaml benchmarks were close to C/C++ speeds because of the heavy use of OCaml's imperative constructs (rather than writing functional style implementations of the code).

In my experience with OCaml, you can write efficient code that approaches C/C++ speeds if you know how functional language compilers work. The biggest performance killer in functional languages is efficiently implementing closures on a stack based machine (i.e. funarg problem). OCaml is smart in that it implements activation records on the stack if it can tell that a function won't return a closure. If you're writing in a heavily functional style, you'll inherently create a lot of closures and lots of heap-based activation records (i.e. less efficient). At the same time, the compiler can do a lot of interesting optimizations that would be difficult in an imperative language. Pretty much every OCaml book including the official manual describes all the various places where you can have performance penalties and what OCaml is doing underneath the hood. Also like any half decent functional compiler, OCaml performs a lot of inlining which results in huge performance gains.

One thing to note, a big part of the reason why OCaml as well as other ML languages and Haskell have such great performance compared to other functional languages is because of very strict and static typing. For example, one of the interesting restrictions of the OCaml type system when dealing with objects is that you cannot downcast an object once it has been upcast (i.e. like a C++ dynamic_cast). Though this restriction is annoying, the generated code never has to do any runtime type checking - everything is statically verified!