In OCaml, how big is the price of abstraction (i.e. polymorphic functions)-Collection of common programming errors

I’m still in the early phase of learning OCaml and am curious to know what the best way to extract maximum performance out of generic code in OCaml is.

As a small experiment, I’ve written two polymorphic functions: one in C++ and the other in OCaml that find the largest element in a given array.

What I’ve observed is that while in C++ you pay no penalty for this sort of abstraction, the penalty in OCaml is a whopping one degree of magnitude drop in performance. And as an aside, the C++ solution I quickly concocted is more generic that the OCaml one, but I blame that primarily on my inexperience with the language.

My question is the following: how to write and use polymorphic functions in OCaml without paying the huge performance penalty that I’ve just observed?

Another thing I observed for this particular problem is that my functional solution in OCaml was slower than the imperative one, whereas the “functional” solution in C++ suffered no penalties compared to the analogue imperative approach.

C++ code was compiled with g++ -std="c++0x" -O3 -o max_cpp max.cpp, using gcc-4.6.3 and OCaml code with: ocamlopt -o max_ml max.ml using ocamlopt version 3.12.1. Both of the generated executables were 32 bit and run on Ubuntu x64 11.04

I submit the code of both programs.

C++ code (not entirely safe, of course 😉 )

#include 
#include 
#include 
template  T max (T a, T b) {
     return (a>b)? a : b;
}

template  typename I::value_type find_max (I begin, I end) {
    auto max = *begin;
    for (begin++;begin!=end;begin++)
            if (*begin > max) max = *begin;
    return max;
}

template  typename I::value_type find_max1(I begin, I end) {
    return std::accumulate(begin, end, *begin, max< typename I::value_type> );
}

int main(int argc, char ** argv) {
    const size_t nElem = atoi(argv[1]);
    const size_t nIter = atoi(argv[2]);
    std::vector intA(nElem);
    std::vector dubA(nElem);
    for (int i=0;i