Last active
February 14, 2023 21:22
-
-
Save postmodern/d3d22739fb3cb815ee3544c9b92de2e8 to your computer and use it in GitHub Desktop.
Ruby micro-benchmark for static vs. dynamic dispatch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
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
Dynamic dispatch (
send()
with a dynamicString
object) is 4x slower than literal method calls: