Last active
September 6, 2023 08:05
-
-
Save hahmed/12e757eba11e87e7830daba4e7c91580 to your computer and use it in GitHub Desktop.
Structs vs classes
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
# SORBET_RUNTIME_DEFAULT_CHECKED_LEVEL=never RUBY_YJIT_ENABLE=1 ruby structs_test.rb | |
# SORBET_RUNTIME_DEFAULT_CHECKED_LEVEL=never ruby structs_test.rb | |
# SORBET_RUNTIME_DEFAULT_CHECKED_LEVEL=always ruby structs_test.rb | |
require "bundler/inline" | |
gemfile(true) do | |
source "https://rubygems.org" | |
git_source(:github) { |repo| "https://github.com/#{repo}.git" } | |
gem "sorbet", "~> 0.5.11002" | |
gem "benchmark-ips" | |
gem "sorbet-runtime", "~> 0.5.11002" | |
end | |
require 'sorbet-runtime' | |
class Entity < T::Struct | |
const :id, Integer | |
const :kind, String | |
end | |
Entity2 = Struct.new(:id, :kind) | |
Entity3 = Data.define(:id, :kind) | |
class Entity4 | |
extend T::Sig | |
sig { returns(Integer) } | |
attr_reader :id | |
sig { returns(String) } | |
attr_reader :kind | |
sig { params(id: Integer, kind: String).void } | |
def initialize(id, kind) | |
@id = id | |
@kind = kind | |
end | |
end | |
Benchmark.ips do |x| | |
x.report("T::Struct") do | |
Entity.new(id: 1, kind: "shop") | |
end | |
x.report("Struct") do | |
Entity2.new(1, "test") | |
end | |
x.report("Data") do | |
Entity3.new(1, "test") | |
end | |
x.report("Class") do | |
Entity4.new(1, "test") | |
end | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment