From: Jon Egil Strand Date: 2007-02-02T04:16:45+09:00 Subject: Performance hit of define_method 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? Hints, comments, links, everything is appreciated. All the best Jon Egil Strand The benchmark code is as follows: ---------------------- 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 @personalia .each_key do |k| self.class.send(:define_method, k) { @personalia[k] } end 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 ---------------------- And the full results goes like this: Rehearsal --------------------------------------------- Static: 0.984000 0.047000 1.031000 ( 1.047000) Dynamic: 21.766000 0.094000 21.860000 ( 21.906000) ----------------------------------- total: 22.891000sec user system total real Static: 1.031000 0.000000 1.031000 ( 1.031000) Dynamic: 21.375000 0.109000 21.484000 ( 21.500000) (Sorry for the naming, I know it's not _static_ per se, but it was a useful label at the time :-) )