[Haskell-cafe] Timing difference

wren ng thornton wren at freegeek.org
Mon Dec 29 21:44:03 EST 2008

Aai wrote:
> Hi Bulat,
> That I (can) understand, but of course the main question is: is point
> free in (some/several/all) cases faster than the more readable lambda
> construction? That's to say when executed in GHCi. I noticed this
> behavior before (pity I haven't other examples at hand). In prog. lang.
> J ( http://www.jsoftware.com/index.html ) I see the same behavior
> difference with tacit (like point free) and explicit programming: tacit
> being faster in several (not all) occasions.

In general point-free will be marginally faster because:

     foo = \x -> ...

defines foo as a constant, whereas:

     foo x = ...

defines (foo x) to be constant for a given x. This subtle distinction 
makes for small differences in the runtime which add up eventually.

The performance difference here is what's at stake when people talk 
about "the monomorphism restriction". Without a type signature to 
indicate otherwise, the point-free/lambda version is forced to be 
monomorphic because it "looks like a constant". Whereas the second 
version could be hiding the fact that we can't do unboxing of x, or that 
we need to locate type-class dictionaries based on the type of x, etc.

All that said, these differences are things which should only matter in 
GHCi and should never affect compiled code. GHC does a lot of analysis 
and does eta-expansion/-reduction in order to make the compiled code 
optimal. If you ever notice a difference in performance from compiled 
code, the GHC developers would love to hear about it I'm sure. I'm less 
familiar with Hugs' optimizations, but you probably shouldn't notice any 
difference there either.

In any case, you should always use whichever style is clearest. A few 
microseconds here or there isn't worth the extra minutes it takes to 
understand your own code six months from now. (And changing your 
algorithms or datastructures will overshadow any micro-optimizations 
like this anyways.)

Live well,

More information about the Haskell-Cafe mailing list