Skip to content

Instantly share code, notes, and snippets.

@postmodern
Last active February 14, 2023 21:22
Show Gist options
  • Save postmodern/d3d22739fb3cb815ee3544c9b92de2e8 to your computer and use it in GitHub Desktop.
Save postmodern/d3d22739fb3cb815ee3544c9b92de2e8 to your computer and use it in GitHub Desktop.
Ruby micro-benchmark for static vs. dynamic dispatch
#!/usr/bin/env ruby
require 'benchmark'
class StaticDispatch
def dispatch
if rand > 0.5
method1
else
method2
end
end
def method1
1
end
def method2
2
end
end
class DynamicDispatch
def dispatch
i = if rand > 0.5
1
else
2
end
send("method#{i}")
end
def method1
1
end
def method2
2
end
end
Benchmark.bm do |b|
n = 1_000_000
b.report('static dispatch') do
obj = StaticDispatch.new
n.times do
obj.dispatch
end
end
b.report('dynamic dispatch') do
obj = DynamicDispatch.new
n.times do
obj.dispatch
end
end
end
#!/usr/bin/env ruby
require 'benchmark'
class StaticDispatch
def dispatch
if rand > 0.5
method1
else
method2
end
end
def method1
1
end
def method2
2
end
end
class DynamicDispatch
def dispatch
method = if rand > 0.5
:method1
else
:method2
end
send(method)
end
def method1
1
end
def method2
2
end
end
Benchmark.bm do |b|
n = 1_000_000
b.report('static dispatch') do
obj = StaticDispatch.new
n.times do
obj.dispatch
end
end
b.report('dynamic dispatch') do
obj = DynamicDispatch.new
n.times do
obj.dispatch
end
end
end
@postmodern
Copy link
Author

and if you were wondering if the overhead was due to String building, dynamic dispatch with Symbols is 2x slower:

       user     system      total        real
static dispatch  0.146822   0.000000   0.146822 (  0.151365)
dynamic dispatch  0.244416   0.000000   0.244416 (  0.245730)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment