From: Paul Brannan Date: 2008-04-23T03:46:06+09:00 Subject: Re: Performance on method dispatch for methods defined via define_method On Wed, Apr 23, 2008 at 12:39:29AM +0900, Robert Dober wrote: > to my dispair (because it makes traits slow) method lookup is about > 50% slower for methods defined via define_method vs. def. > If this is completely stupid a question just say so and sorry for > having wasted your time, but here I go. Why do you believe it is method lookup that is slower? Your benchmark tests both lookup and dispatch (I say this because I suspect it is the dispatch that is slow). > Would there be any chance to get the same speed for method > lookup/invocation for methods defined via define_method? > Right now we have this: Method dispatch to a method defined with define_method is not much less than the cost of calling a proc, which is essentially what's happening under the hood: [pbrannan@zaphod tmp]$ cat test.rb require 'benchmark' N=1_000_000 Benchmark::bmbm do |bm| p = proc { } o = Object.new osc = class << o; self; end osc.instance_eval { define_method(:foo, &p) } bm.report "define_method" do N.times { o.foo } end bm.report "proc.call" do N.times { p.call } end end [pbrannan@zaphod tmp]$ ruby1.9 -v test.rb ruby 1.9.0 (2008-03-20 revision 0) [i686-linux] Rehearsal ------------------------------------------------- define_method 1.090000 0.000000 1.090000 ( 1.095923) proc.call 1.210000 0.000000 1.210000 ( 1.218726) ---------------------------------------- total: 2.300000sec user system total real define_method 1.080000 0.020000 1.100000 ( 1.106690) proc.call 1.210000 0.000000 1.210000 ( 1.219874) To make methods defined with define_method faster, one would need to make proc invocation faster. I don't see any low-hanging fruit here, though. It's already much faster than 1.8: [pbrannan@zaphod tmp]$ ruby -v test.rb ruby 1.8.6 (2007-09-24 patchlevel 111) [i686-linux] Rehearsal ------------------------------------------------- define_method 3.190000 0.000000 3.190000 ( 3.196841) proc.call 3.250000 0.010000 3.260000 ( 3.255551) ---------------------------------------- total: 6.450000sec user system total real define_method 3.210000 0.000000 3.210000 ( 3.210368) proc.call 3.280000 0.000000 3.280000 ( 3.284931) Paul