[Haskell-cafe] Performance Issue

Richard Warburton richard.warburton at gmail.com
Tue May 18 12:30:56 EDT 2010


A colleague of mine pointed out that ghc wasn't performing as he
expected when optimising some code.  I wonder if anyone could offer
any insight as to why its not noting this common subexpression:

main = print $ newton 4 24

newton a 0 = a
newton a n =  ((newton a (n-1))^2 + a)/(2*(newton a (n-1)))

Compiled with 'ghc -O3 --make perf.hs', results in:

real    0m5.544s
user    0m5.492s
sys     0m0.008s

However if we factor out the repeated call to the newton method:

main = print $ newton2 4 24

newton2 a 0 = a
newton2 a n =  (x^2 + a)/(2*x)
        where
          x = newton2 a (n-1)

real    0m0.004s
user    0m0.004s
sys     0m0.004s

It looks to me like Referential transparency should make this a sound
optimisation to apply, but ghc isn't doing it even on -O3.

regards,

  Richard


More information about the Haskell-Cafe mailing list