问题
Possible Duplicate:
Memory footprint of Haskell data types
When solving combinatorial problems, I will often represent the solution as a bit string, eg. 1010100010110111000110... You get the picture.
I figured that when I use [Int]
for the bit string, Int
always spends the same amount of memory, no matter how big the number actually is (because Int
it's bounded, in contrast to Integer
), as the computer only remembers the bit representation, and String
's would take even more space as far as I know.
My idea was then to use the data type
data Bits = Empty | Zero Bits | One Bits deriving (Eq,Ord,Show)
But how much memory do the constructors Empty
, Zero
and One
use compared to Int
's?
回答1:
Int
costs two words in memory (#I
constructor and #Int
field), your Bits
data can use various cost, for example: Zero (One (Zero Empty))
will cost:
- One word for
Empty
constructor - Two words for
Zero
Constructor and field - Two words for
One
Constructor and field - Two words for
Zero
Constructor and field
and total cost — 7 words.
So memory amount for your data can be more than for Int
.
来源:https://stackoverflow.com/questions/12245410/memory-usage-of-constructors-in-haskell