Skip to content

Instantly share code, notes, and snippets.

@postmodern
Last active June 13, 2024 00:32
Show Gist options
  • Save postmodern/8db319b71a628ca23727e9a8c31e45e5 to your computer and use it in GitHub Desktop.
Save postmodern/8db319b71a628ca23727e9a8c31e45e5 to your computer and use it in GitHub Desktop.
Benchmarking if / else with kind_of? against case / in to match two values based on their classes. if / else + kind_of? appears to be 4x faster.
ruby 3.2.4 (2024-04-23 revision af471c0e01) [x86_64-linux]
Warming up --------------------------------------
if / else 888.000 i/100ms
case / in 259.000 i/100ms
Calculating -------------------------------------
if / else 8.856k (± 0.9%) i/s - 44.400k in 5.013974s
case / in 2.560k (± 3.0%) i/s - 12.950k in 5.064976s
#!/usr/bin/env ruby
require 'benchmark/ips'
class Foo
end
class Bar
end
value1 = Foo.new
value2 = Bar.new
Benchmark.ips do |b|
n = 1_000
b.report('if / else') do
n.times do
result = if (value1.kind_of?(Foo) && value2.kind_of?(Bar))
true
else
false
end
end
end
b.report('case / in') do
n.times do
result = case [value1, value2]
in [Foo, Bar]
true
else
false
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment