In my Haskell code i use a function that gets very often called and looks like this:
doSomething x y = (a, b)
where a = expensive1 x y
b = expensive2 x y a
Compiled with GHC 8.10.3 and -O2 my program takes about 45 seconds to run. However if i write the same function like this:
doSomething x y = (a, b)
where a = expensive1 x y
b = expensive2 x y (expensive1 x y)
my program takes about 60 seconds to run.
Shouldn't the compiler recognize the duplicate call of expensive1 x y and optimize it away? expensive1 and expensive2 are pure functions, so recalculating expensive1 x y shouldn't be necessary. Or is the GC too aggressive and garbage collects a before before b is needed later?