[Haskell-beginners] Int V.S. Word32

Daniel Fischer daniel.is.fischer at googlemail.com
Sat Nov 19 15:49:15 CET 2011


On Saturday 19 November 2011, 09:09:50, Haisheng Wu wrote:
> Hello,
>   I got great performance difference for the following code if I used
> type `Int` rather than `Data.Word.Word32`.
>   Anyone can help to explain why such difference?

Short answer: GHC optimises Int calculations far better than Word32 
calculations, rather, it optimises more calculations for Int than for 
Word32.  It also optimises more calculations for Word than for Word32, but 
not as many as for Int.

The reason is that Int (and Word) are (at least expected to be) far more 
often used, so the effort has gone to these types primarily. Work is being 
done to get the fixed-width types on par, but it's not around the corner 
yet.

You can try using Word instead of Word32, that's likely to be faster.

But

>   Thanks a lot.
> 
> -Simon
> 
> module Main where
> import Data.Word
> 
> main :: IO ()
> main = print $ p14
> 
> p14 = maximum [ (startChain n 0, n) | n <- [2..1000000] ]

You get overflow using 32-bit types here.

> 
> startChain :: Word32 -> Int -> Int
> startChain 1 count    = count + 1
> startChain n count    = startChain (intTransform n) (count+1)
> 
> intTransform :: Word32 -> Word32
> intTransform n
> 
>   | even n         = n `div` 2
>   | otherwise      = 3 * n + 1




More information about the Beginners mailing list