haskell array access

Lex Stein stein@eecs.harvard.edu
Thu, 26 Jun 2003 17:48:17 -0400 (EDT)


Hi, I'm measuring Haskell, Ocaml, and C, small array access performance
and the results with Haskell (GHC 5.02.2) are so bad that I think I must
be doing something wrong. Indeed, I am hardly a seasoned Haskell
programmer. My results are:

ghc -O      61.60s
gcc -O3      0.20s
Ocamlopt     1.11s (tail call)
Ocamlopt     0.82s (for loop)

Why is the ghc generated code so slow? The source for all the tests is
below. Any insight will be greatly appreciated (I'm running on Debian
Linux w/ 1GHz x86 CPU and 768MB RAM).

The test cycles through an array of 16 elements, reading 100*10^6
elements.

Thanks!
Lex

Haskell (ghc5) test source:

import Array
k = Array.array (0,15) [(i, i+1) | i <- [0 .. 15] ]
acc 0 = 0
acc n = seq (k Array.! (n `mod` 16)) (acc (n-1))
main = do
        print (acc 100000000)

C (gcc) test source:

int main () {
        int i, k;
        int a [16];
        for (i=0; i<=100000000; i++) {
                k = a [i % 16];
        }
}

Ocaml test source (tail call):

let a = Array.make 16 0;;
let rec do1 i =
        if (i>100000000) then () else
        let k = a.(i mod 16) in
                do1 (i+1);;
do1 0;;

Ocaml test source (for loop):

let a = Array.make 16 0;;
for i=0 to 100000000 do
        let k = a.(i mod 16) in ()
done