Haskell: Unboxed vs. boxed

Posted by Moser on 03 Apr 2012

Because I did not find a good example (at least not on the first result page :D) for the performance difference between boxed and unboxed types in Haskell, I created one.

--boxed.hs
foo :: Int -> Int
foo 0 = 0
foo n = foo (n - 1)

main = print (foo 500000000)
--unboxed.hs
import GHC.Exts
foo :: Int# -> Int#
foo 0# = 0#
foo n = foo (n -# 1#)

main = print (I# (foo 500000000#))

And here is the quite impressive result:

$ ghc boxed.hs
$ ghc -XMagicHash unboxed.hs
$ time ./boxed
0
./boxed  16,34s user 0,03s system 99% cpu 16,397 total
$ time ./unboxed
0
./unboxed  0,85s user 0,00s system 99% cpu 0,865 total
blog comments powered by Disqus