On Fri, 2 Feb 2007, Jon Egil Strand wrote:

>
> Greetings
>
> I've ran into some performance trouble using define_method.
>
> Benchmarking gives:
>
> With    define_method:  1 second
> Without define_method: 21 seconds
>
>
> Question:
>
> Is this to be expected, or am I doing something totally or partially
> wrong?


it's not so much the fact that you are using define_method, which is a bit
slow, but the fact that one Staticperson you define the methods on once while
in Dynamicperson you define the methods each and every time even though the
def simply clobbers the existing one.  if you want to compare apples with
apples then:

     harp:~ > ruby a.rb
     Rehearsal ---------------------------------------------
     Static:     0.630000   0.000000   0.630000 (  0.622125)
     Dynamic:    1.080000   0.000000   1.080000 (  1.573303)
     ------------------------------------ total: 1.710000sec

     user     system      total        real
     Static:     0.600000   0.000000   0.600000 (  1.086655)
     Dynamic:    1.050000   0.000000   1.050000 (  1.179166)



     harp:~ > cat a.rb
     class Staticperson
       def initialize(personalia)
         @firstname = personalia[:firstname]
         @surname = personalia[:surname]
         @country = personalia[:country]
       end
       attr_reader :firstname, :surname, :country
     end

     class Dynamicperson
       def initialize personalia
         @personalia = personalia
       end
       [:firstname, :surname, :country].each do |k|
         define_method(k){ @personalia[k] }
       end
     end

     peter = {:firstname => "Peter",
              :surname => "Pan",
              :country => "Neverland"}

     COUNT = 100_000

     require 'benchmark'

     Benchmark.bmbm do |test|
      test.report("Static: ") do
        COUNT.times do
          s_peter = Staticperson.new(peter)
          s_peter.firstname
          s_peter.surname
          s_peter.country
        end
      end
      test.report("Dynamic: ") do
        COUNT.times do
          d_peter = Dynamicperson.new(peter)
          d_peter.firstname
          d_peter.surname
          d_peter.country
        end
      end
     end



regards.

-a
-- 
we can deny everything, except that we have the possibility of being better.
simply reflect on that.
- the dalai lama