Skip to content

Instantly share code, notes, and snippets.

@TylerBrock
Last active December 17, 2015 14:49
Show Gist options
  • Save TylerBrock/5627769 to your computer and use it in GitHub Desktop.
Save TylerBrock/5627769 to your computer and use it in GitHub Desktop.
Ruby Method Call Speed based on Definition Strategy
require 'benchmark/ips'
GC.disable
class Foo
def baz; end
define_method(:foo) { }
class_eval 'def bar; end'
end
Benchmark.ips do |x|
foo = Foo.new
x.report('def') { foo.baz }
x.report('define_method') { foo.foo }
x.report('class_eval') { foo.bar }
end

Facts

On MRI 2.0.0-p195 calling methods defined via class_eval is faster calling than methods defined via define_method

Calculating -------------------------------------
      define_method     88666 i/100ms
         class_eval     92198 i/100ms
-------------------------------------------------
      define_method  4051462.7 (±0.8%) i/s -   20304514 in   5.011990s
         class_eval  5508583.8 (±0.2%) i/s -   27567202 in   5.004426s

On MRI 2.0.0-p195 it's also just as fast as calling methods defined via def

Calculating -------------------------------------
             def     92317 i/100ms
   define_method     88130 i/100ms
      class_eval     92069 i/100ms
-------------------------------------------------
             def  5104345.9 (±2.4%) i/s -   25571809 in   5.012518s
   define_method  3819747.0 (±2.2%) i/s -   19124210 in   5.009052s
      class_eval  5087196.2 (±2.0%) i/s -   25503113 in   5.015126s

The same thing is true on JRuby 1.7.3

Calculating -------------------------------------
             def    153386 i/100ms
   define_method    149121 i/100ms
      class_eval    203329 i/100ms
-------------------------------------------------
             def  7117137.2 (±4.4%) i/s -   35585552 in   5.012000s
   define_method  3661552.3 (±1.8%) i/s -   18341883 in   5.011000s
      class_eval  7229081.1 (±2.2%) i/s -   36192562 in   5.009000s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment