From: Robert Klemme Date: 2006-03-29T03:59:06+09:00 Subject: Re: New Optimization idea. John Carter wrote: > I have a couple of classes like so... > > class Foo > def step1 > @mine = Hash.new > # Perhaps stuff things into @mine > end > > def step2 > @mine.each_pair do |key,value| > # Do stuff > end > end > end > > Profiling with my "new" profiler shows that I'm creating many many Hash > objects, probably way more than I need. In fact most of them are empty. > > Optimization trick... > > > class Object > FROZEN_EMPTY_HASH = Hash.new.freeze > end > > class Foo > @@hash_cache = Hash.new > > def step1 > @mine = @@hash_cache > # Perhaps stuff things into @mine > if @mine.empty? > @mine = FROZEN_EMPTY_HASH > else > @@hash_cache = Hash.new > end > end > > def step2 > @mine.each_pair do |key,value| > # Do stuff > end > end > end You could as well leave the member nil and change the getter appropriately: class Foo def mine() @mine || FROZEN_EMPTY_HASH end def step2() mine.each_pair ... end Or do the test in step2... @mine and @mine.each_pair ... Kind regards robert