Last active
November 3, 2023 10:45
-
-
Save benoittgt/6cba7edf579057688acd42055f3cf6bb to your computer and use it in GitHub Desktop.
Struct.new VS Data.define
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
require 'benchmark/ips' | |
DataS = Struct.new(:encoder, :values) do # :nodoc: | |
def hash | |
[encoder, values].hash | |
end | |
end | |
DataD = Data.define(:encoder, :values) do # :nodoc: | |
def hash | |
[encoder, values].hash | |
end | |
end | |
DataDkw = Data.define | |
class DataDCkw < DataDkw | |
def initialize(encoder:, values:) | |
@encoder = encoder | |
@values = values | |
end | |
def hash | |
[@encoder, @values].hash | |
end | |
end | |
Benchmark.ips do |x| | |
x.report("Struct.new") do | |
DataS.new("CSV", [1,2,3]).hash | |
end | |
x.report("Data.define") do | |
DataD.new("CSV", [4,5,6]).hash | |
end | |
x.report("Data.define kw") do | |
DataDCkw.new(encoder: "CSV", values: [7,8,9]).hash | |
end | |
x.compare! | |
end | |
=begin | |
Warming up -------------------------------------- | |
Struct.new 291.475k i/100ms | |
Data.define 219.096k i/100ms | |
Data.define kw 170.260k i/100ms | |
Calculating ------------------------------------- | |
Struct.new 2.930M (± 0.3%) i/s - 14.865M in 5.073303s | |
Data.define 2.204M (± 0.4%) i/s - 11.174M in 5.070686s | |
Data.define kw 1.703M (± 0.3%) i/s - 8.683M in 5.097443s | |
Comparison: | |
Struct.new: 2930109.7 i/s | |
Data.define: 2203663.3 i/s - 1.33x slower | |
Data.define kw: 1703469.8 i/s - 1.72x slower | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Different output if we look only at initialization, but I think we do less.