[Haskell-cafe] How can we detect and fix memory leak due tolazyness?

Brian Hulley brianh at metamilk.com
Mon Aug 7 21:27:42 EDT 2006


Ahn, Ki Yung wrote:
> Recently, I'm facing the dark side of laziness
> -- the memory leak because of laziness.

> The following is the code that leaks memory.
>
> sctAnal gs = null cgs || all (not . null) dcs
> where
>   gs' = fixSize compose $ Set.fromList [TT (x,y,cs) [] | To _ x y
> cs<-Set.toList gs]
>   cgs = [z | z@(TT (x,y,cs) _)<-Set.toList gs', x==y]
>   dcs = [[c| c@(a,D,b)<-Set.toList cs , a==b] | TT (_,_,cs) _<-cgs]
>   compose gs = trace ("## "++show (Set.size gs)) $ foldr checkInsert

One thing is that (foldr) is not recommended if you can at all avoid it. I 
think you may be able to use (foldl') here (if you also swap the arg order 
for checkInsert) which behaves as a strict fold operation so it doesn't 
waste space building up thunks.

>     gs $ do TT (x1,y1,cs1) l1 <- Set.toList gs
>     TT (_,y2,cs2) l2 <- takeWhileTTfrom y1 . Set.toList $ setGT (TT
> (y1,Al""(-1),Set.empty) []) gs
>     return $ TT (x1,y2,cs1 `comp` cs2) (l1++y1:l2)
>   takeWhileTTfrom y = takeWhile (\(TT (y',_,_) _) -> y==y')
>   checkInsert x s

           -- checkInsert s x -- if you use foldl'

>                   | Set.member x s = s
>                   | otherwise      = Set.insert x s

Sorry I can't help more at the moment -

Regards, Brian.
-- 
Logic empowers us and Love gives us purpose.
Yet still phantoms restless for eras long past,
congealed in the present in unthought forms,
strive mightily unseen to destroy us.

http://www.metamilk.com 



More information about the Haskell-Cafe mailing list