From: John Carter Date: 2004-11-01T12:58:27+09:00 Subject: Nuby Tip for the Day : Memoization So you have written your ruby app. It works. So you throw it at a really Big Problem....and it grinds to a halt. Too slow, too much memory. If I find I that keep recreating an object, here is a trick that I sometimes play... Replace... ------------- class BigExpensiveMadeOften def initialize( unique_name) # Big expensive computation end end . . . # Some Inner Loop bem = BigExpensiveMadeOften.new( unique_name) ------------- with... class BigExpensiveMadeOften def initialize( unique_name) # Big expensive computation end @@memo = Hash.new {|hash,key| result = BigExpensiveMadeOften.new( unique_name) hash[key] = result } def BigExpensiveMadeOften.create( unique_name) return @@memo[unique_name] end end . . . # Some Inner Loop bem = BigExpensiveMadeOften.create( unique_name) ------- and hey presto, instead of recreating a BigExpensiveMadeOften object every time, it just immediately returns one of them out of the memo cache. Really an easy optimization to do. John Carter Phone : (64)(3) 358 6639 Tait Electronics Fax : (64)(3) 359 4632 PO Box 1645 Christchurch Email : john.carter@tait.co.nz New Zealand The universe is absolutely plastered with the dashed lines exactly one space long.