Skip to content

Instantly share code, notes, and snippets.

@waymondo
Created July 24, 2023 14:40
Show Gist options
  • Save waymondo/2d49903c5134ec6bcf9745283b0449a2 to your computer and use it in GitHub Desktop.
Save waymondo/2d49903c5134ec6bcf9745283b0449a2 to your computer and use it in GitHub Desktop.
Comparing Ruby Struct / Data / Class
require "benchmark/ips"
require "attr_extras"
first_name = "John"
last_name = "Brown"
module FullName
def full_name
[first_name, last_name].compact.join(" ")
end
end
PersonStruct = Struct.new(:first_name, :last_name) do
include FullName
end
PersonData = Data.define(:first_name, :last_name) do
include FullName
end
class PersonClass
include FullName
rattr_initialize([:first_name!, :last_name!])
end
Benchmark.ips do |x|
x.report("Struct") do
PersonStruct.new(first_name:, last_name:).full_name
end
x.report("Data") do
PersonData.new(first_name:, last_name:).full_name
end
x.report("Class") do
PersonClass.new(first_name:, last_name:).full_name
end
x.compare!
end
@waymondo
Copy link
Author

Results (on a 2021 MBP M1 Pro):

% ruby ./test.rb
Warming up --------------------------------------
              struct   228.785k i/100ms
                data   233.660k i/100ms
               class    54.026k i/100ms
Calculating -------------------------------------
              struct      2.268M (± 0.7%) i/s -     11.439M in   5.042982s
                data      2.323M (± 0.4%) i/s -     11.683M in   5.028805s
               class    534.817k (± 0.6%) i/s -      2.701M in   5.051091s

Comparison:
                data:  2323263.1 i/s
              struct:  2268469.1 i/s - 1.02x  slower
               class:   534816.9 i/s - 4.34x  slower

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