Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible GHCI displays used memory of bigger value than I physically have?

The basic question comes along with the quotes from the GHCI interpreter. Yes, I know that the supposed use of code is compiling it into executable, however, as I am a beginner in Haskell, GHCI seems to be perfect to learn some Haskell.

When I use the heavy-computational load algortihms, I sometimes come across messages like the following:

Prelude Data.List> foldl' (+) 0 [1..2*10^8]
20000000100000000
it :: (Num b, Enum b) => b
(8.35 secs, 17,600,063,056 bytes)

At the same time, I only have 8 GB of RAM physically installed.

If memory usage is over a certain limit (which I'm not quite sure how many that is, but suggest that's all memory that can be used), the Stack Overflow exception is thrown, like illustrated below:

Prelude> foldl (+) 0 [1..5 * 10^7]
*** Exception: stack overflow

However, how is it possible that the program uses > 16 GBs of memory while my RAM is totalling to 8 GB and that without throwing Stack Overflow exception?

like image 693
Nick M Avatar asked Mar 07 '19 12:03

Nick M


1 Answers

The magic of garbage collection: the number reported by :set +s that you show tells the total number of bytes requested from the allocator, even if they were later deallocated and returned to the allocator to be reused before the computation finished.

like image 150
Daniel Wagner Avatar answered Nov 06 '22 20:11

Daniel Wagner