Does Haskell optimizer utilize memoization for repeated function calls in a scope?

二次信任 提交于 2019-12-01 15:21:05
Don Stewart

GHC now does some CSE by default, as the -fcse flag is on.

On by default.. Enables the common-sub-expression elimination optimisation. Switching this off can be useful if you have some unsafePerformIO expressions that you don't want commoned-up.

However, it is conservative, due to the problems with introducing sharing (and thus space leaks). The CSE pass is getting a bit better though (and this).

Finally, note there is a plugin for full CSE.

If you have code that could benefit from that.

Even in such a local setting, it is still the case that it is not obvious that the introduction of sharing is always an optimization. Consider this example definition

f = if length [1 .. 1000000] > 0 then head [1 .. 1000000] else 0

vs. this one

f = let xs = [1 .. 1000000] in if length xs > 0 then head xs else 0

and you'll find that in this case, the first behaves much better, as each of the computations performed on the list is cheap, whereas the second version will cause the list to be unfolded completely in memory by length, and it can only be discarded after head has been reduced.

The case you are describing has more to do with common subexpression elimination than memoization, however it seems that GHC currently doesn't do that either because unintended sharing might lead to space leaks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!