From: Stefano Crocco Date: 2007-09-18T19:08:27+09:00 Subject: Re: how to use tuple as hash key Alle marted狸 18 settembre 2007, SpringFlowers AutumnMoon ha scritto: > SpringFlowers AutumnMoon wrote: > > but my question is, if i run the loop 10 million times (for some > > statistics), then it will actually duplicate the array 10 million times, > > which is memory hungry. > > actually, i tried running it and watch ruby.exe in Windows or ruby in > Mac keep on being 2 or 3MB without every growing. (i set the loop to > 100 million and dup the key and watched it keep on running with the > program size about the same while running). > > I think it is due to the hash table's size is constant. so when Hash > called hash() to find the slot, and do the eql? and find that they are > the same. and so it either places that dup key in that slot or don't > place it there at all (doesn't matter), and the un-referenced > dupulicates are garbage collected. so that's why the size of the > program keep on being 2 to 3MB in the RAM. > > if however, i set an array just_test and always do a just_test << > key where key is the dup, then the program will grow from 3MB to 6MB, > to 12MB, to 20MB and it just keeps growing. (just_test is an array to > keep a reference to the dup objects so that they won't be garbage > collected). So looks like the garbage collection in Ruby is doing a > good job. I think it's easier (and more efficient) to create a new array with the current values of i and j at each iteration, instead of modifying one single array and duping it. for i in 1..2 for j in 1..2 h2[[i,j]] = "ha" end end Stefano