Last active
July 7, 2024 07:03
-
-
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.
This file contains hidden or 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
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 |
This file contains hidden or 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/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
Ah yes, interstingly after doing
The results are almost the same: