Jeremy Henty
8/8/2006 12:17:00 AM
On 2006-08-07, Sam Kong <sam.s.kong@gmail.com> wrote:
> (1..100000).each {|i|...}
>
> Now there are 100000 integers in the memory which won't die.
No there aren't. Immediate values don't allocate anything in memory.
They aren't pointers (even though under the hood Ruby coerces them to
the same type as non-immediate values that *are* pointers). Immediate
values aren't garbage collected because there is *nothing* to garbage
collect. They don't point to anything. What is there to collect?
Think of C. Does "long i ; i = 0 ; i = 1 ; i = 2 ; i = 3" consume any
more memory than "long i ; i = 0"? No, because the only memory
allocated is for the long variable "i". The values 0, 1, 2, 3, are
just constants that are copied (one after the other) into that single
previously allocated space. Ruby's immediate values are just like C
longs (in fact, under the hood, they *are* just C longs). Creating
them doesn't consume memory, it just copies them into a pre-existing
chunk of memory that was already allocated by the Ruby interpreter.
If you create lots of *references* to immediate values, eg. by writing
" a = (1..100000).collect {|i| i } ", then that *will* consume memory.
But that memory isn't being used to create immediate values, it's
being used to store those values inside an object. Once that object
is no longer referenced the memory is available to be recycled by the
garbage collector. All memory allocation/deallocation is associated
with the non-immediate object that holds those references. The
immediate values themselves allocate no memory at all.
Regards,
Jeremy Henty