From ruby-core Wed Apr 07 13:08:29 2010 From: Ken Bloom Date: Wed, 07 Apr 2010 13:08:29 +0000 To: ruby-core Subject: [ruby-core:29299] Re: Proposal: Module#thunk_method Message-Id: X-MARC-Message: https://marc.info/?l=ruby-core&m=127064581421771 On Tue, 06 Apr 2010 09:42:30 +0900, Charles Oliver Nutter wrote: > Many people use define_method solely so they can define a new method > that just returns a value, such as for memoization. Unfortunately > define_method is a full block dispatch, and as a result it can be a lot > slower than regular method calls. > > I propose a new method Module#thunk_method which defines a > fast-as-possible method that just returns the value you give it: > > class Foo > thunk_method :value, "some value" > end > > Foo.new.value # => "some value" > > This would eliminate define_method cases like this: > > # lazy-memozing value method > def value > a = some_expensive_calculation > self.class.class_eval {define_method(:value) {a}} > end > > Thoughts? Should this go into RedMine? > > - Charlie If this optimization is worthwhile, then shouldn't the Ruby interpreter do some sort of static analysis on the closure and the local variable to identify this case and give you the performance boost while still using the define_method API? -- Chanoch (Ken) Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/