Rados• £¬w Bu• £¬t wrote:

> <code>
> def leaker
>   a = Array.new(1_000_000) {|i| "blah"}
> end
> 
> loop do
>   printf "%10s", `ps h -o rss #{$$}`
>   leaker
> end
> </code>
> 
> Why this program doesn't cause memory leaks?

Beacuse in this program

<code>
a = ""
10000.times do
   a = a + "buble"
end
</code>

in each cycle ruby creates a new string with length:
<No. of cycle> * "buble".length + 1 ('\0')

No. of cycle   Heap
------------   ----------
1)             a = "buble"
2)             a = "bublebuble" , a' = "buble"
3)             a = "bublebublebuble", a' = "bublebuble", a'' = "buble"
etc.

so after n-cycles we have
    S = n * (("buble".length + 1) + (("buble".length * n + 1)) / 2
in my program:
    n = 10000
    "buble".size = 5
    S = 10000 * (5 + 1 + 50000 + 1)/2 = 5000 * 50007 = 250_035_000 bytes

In your program the strings occupy only
  1_000_000 * ("blah".length + 1) = 6_000_000 bytes
-- 
Posted via http://www.ruby-forum.com/.