Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Created July 24, 2012 11:37
Show Gist options
  • Save jgaskins/3169504 to your computer and use it in GitHub Desktop.
Save jgaskins/3169504 to your computer and use it in GitHub Desktop.
Compare performance of polymorphic vs if-guarded method dispatch

What is this?

I decided to compare the performance of using if-based execution against actual polymorphic method calls on the big 3 Ruby implementations. The results on MRI were what I expected across all of them — that is, polymorphism being much faster. The results are across 1M objects in an array.

In the case of MRI 1.9, dynamic dispatch is 58% faster than explicit if-based branching. On JRuby, the runtimes are nearly identical. And on Rubinius, polymorphic calls are slightly faster (about 25%).

MRI 1.9

                  user     system      total        real
if            0.200000   0.000000   0.200000 (  0.202083)
polymorphic   0.130000   0.000000   0.130000 (  0.127721)

JRuby 1.7 (Java 7)

                  user     system      total        real
if            0.080000   0.010000   0.090000 (  0.075000)
polymorphic   0.110000   0.020000   0.130000 (  0.074000)

Rubinius

                  user     system      total        real
if            0.206464   0.000040   0.206504 (  0.206511)
polymorphic   0.164807   0.000022   0.164829 (  0.164837)
require 'benchmark'
object_count = 1_000_000
class Stuff
def call_me_maybe?
end
def stuff_specific_method
end
end
class Thing
def call_me_maybe?
end
def thing_specific_method
end
end
objects = (1..object_count).map{rand < 0.5 ? Stuff.new : Thing.new }
Benchmark.bmbm do |x|
x.report('if ') do
objects.each do |o|
if o.is_a? Thing
o.thing_specific_method
elsif o.is_a? Stuff
o.stuff_specific_method
end
end
end
x.report('polymorphic') do
objects.each { |o| o.call_me_maybe? }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment