[Haskell-cafe] GHC magic optimization ?
lrpalmer at gmail.com
Fri Dec 4 05:43:27 EST 2009
On Fri, Dec 4, 2009 at 3:36 AM, Neil Brown <nccb2 at kent.ac.uk> wrote:
> But let's say you have:
> g x y = f x y * f x y
> Now the compiler (i.e. at compile-time) can do some magic. It can spot the
> common expression and know the result of f x y must be the same both times,
> so it can convert to:
> g x y = let z = f x y in z * z
GHC does *not* do this by default, quite intentionally, even when
optimizations are enabled. The reason is because it can cause major
changes in the space complexity of a program. Eg.
x = sum [1..10^6] + product [1..10^6]
x' = let l = [1..10^6] in sum l + product l
x runs in constant space, but x' keeps the whole list in memory. The
CSE here has actually wasted both time and space, since it is harder
to save [1..10^6] than to recompute it! (Memory vs. arithmetic ops)
So GHC leaves it to the user to specify sharing. If you want an
expression shared, let bind it and reuse.
More information about the Haskell-Cafe