The two steps you must follow are:
- Is compiled code being executed, not in ghci?
- You use the -O2 flag
The following criteria were met by the criterion and used the following functions along with the length of the prelude , which requires MagicHash pragma and importing GHC.Base
myLength1 :: [a] -> Int myLength1 [] = 0 myLength1 (x:xs) = 1 + myLength1 xs myLength2 :: [a] -> Int myLength2 lst = len lst 0 where len :: [a] -> Int -> Int len [] n = n len (_:xs) n = len xs (n+1) myLength3 :: [a] -> Int myLength3 l = len l 0
Results of a test fully found at the end using the -O2 tag:
mean length : 5.4818 ms myLength1 : 202.1552 ms myLength2 : 236.3042 ms myLength3 : 5.3630 ms
Now let's use the -02 flag when compiling
mean length : 5.2597 ms myLength1 : 12.882 ms myLength2 : 5.2026 ms myLength3 : 5.6393 ms,
Note that the length of myLength3 does not change, but the other two vary significantly. The naive approach is in 3 different myLength2 , and myLength2 now matched with the built-in length, simulating the length of the foreplay in all but using unboxing.
Also note that myLength3, which decompresses Int, does not change much and it will probably be much better to generate myLength 1 or 2 in ghci.
Full code: https://gist.github.com/Davorak/5457105
Edit: some additional information that does not fit into the comment:
The ghc -O2 flag with the letter means "Apply every non-hazardous optimization, even if it means significantly longer compilation times." I won’t be surprised if this involves unpacking data types. You can find additional explanations of the various flags here . Here is a link with a large list of flags for ghc 7.6.2 explanations can be short and cryptic.
I am not very familiar with unpacking and primitive operations, and their implications here are the third reference to the GHC manual , which covers unpacked types. Sometimes you will mention them in optimization manuals. In most cases, you should not worry about them unless you really need every gram of performance, because, as we said above, they will often make a constant difference after using other optimization flags.