Created
July 24, 2023 14:40
-
-
Save waymondo/2d49903c5134ec6bcf9745283b0449a2 to your computer and use it in GitHub Desktop.
Comparing Ruby Struct / Data / Class
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results (on a 2021 MBP M1 Pro):