Memory blowing up for strict sum/strict foldl in ghci

梦想与她 提交于 2019-12-22 12:37:41

问题


As mentioned in Why does (sum $ takeWhile (<10000000) [1..]) use so much memory? the following does not blow up the memory in ghci :

foldl' (+) 0 $ takeWhile (< 10000000) [1 .. ]

However if I create a file containing :

import Data.List

longList::[Int]
longList = [1 .. ]

result :: Int
result = foldl' (+) 0 $ takeWhile (< 10000000) longList

main = do
  print $ result

and load into ghci, then upon running the program the memory consumption blows up. Why is this, and what can I do to fix the program? I am using ghc 7.8.3.

[EDIT]

It does not seem to blow up provided I compile first via ghc Test.hs. But if I remove all the .hi and .o files, and load into ghci via ghci Test.hs then the memory does blow up.


回答1:


I believe this is due to the different treatment of the identifier longList when you :l the file in GHCi, as opposed to when it is compiled.

When you :l ModuleName in GHCi, by default all top-level identifiers in the module come into scope, so that you may debug it efficiently. For your example, this includes longList. This means that GHCi keeps around the content of longList after it has been evaluated, which gives a memory leak. I suspect this is the case even with -fobjectcode, so I am not sure the behavior discussed in the other comments actually is a bug.

When on the contrary you compile the module, GHC uses the module export list to find out which identifiers are exposed in the result. Since you have no explicit module declaration, it defaults to (last paragraph)

module Main (main) where

This means that when compiling, GHC can note that all identifiers except main are not exposed, and that longList is only used once. It can then drop keeping its value around, avoiding the memory leak.




回答2:


See the section on note on GHCI:

If you are noticing a space leak while running your code within GHCi, please note that interpreted code behaves differently from compiled code: even when using seq.

Consider starting ghci as follows:

$ ghci -fobject-code



来源:https://stackoverflow.com/questions/24838982/memory-blowing-up-for-strict-sum-strict-foldl-in-ghci

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