Skip to content

Instantly share code, notes, and snippets.

@jcraigk
Created December 3, 2021 18:02
Show Gist options
  • Save jcraigk/32c6720ddda98a71468a3dcd257591a7 to your computer and use it in GitHub Desktop.
Save jcraigk/32c6720ddda98a71468a3dcd257591a7 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require 'benchmark'
namespace :benchmark do
desc 'Benchmark Hash vs Openstruct vs Struct for a smallish data structure'
task openstruct: :environment do
CYCLES = 1_000
PRINT_EVERY = 50
DATA = {
a: 'foo',
b: 'bar',
c: 'baz',
d: 'weed',
e: 'thc'
}.freeze
Benchmark.bm do |x|
puts 'Hash'
x.report do
CYCLES.times do |i|
obj = JSON.parse(json, symbolize_names: true)
member = DATA.keys.sample
"Value at #{i} for #{member}: #{obj[member]}"
end
end
puts 'OpenStruct'
x.report do
CYCLES.times do |i|
obj = JSON.parse(json, object_class: OpenStruct)
member = DATA.keys.sample
"Value at #{i} for #{member}: #{obj.send(member)}"
end
end
puts 'Struct'
x.report do
CYCLES.times do |i|
obj = JSON.parse(json, object_class: FooStruct)
member = DATA.keys.sample
"Value at #{i} for #{member}: #{obj.send(member)}"
end
end
puts 'Struct with safety slicing'
x.report do
CYCLES.times do |i|
obj = FooStruct.new(JSON.parse(json).slice(*FooStruct.members.map(&:to_s)))
member = DATA.keys.sample
"Value at #{i} for #{member}: #{obj.send(member)}"
end
end
end
end
def json
@json ||= DATA.to_json
end
FooStruct = Struct.new(:a, :b, :c, :d, :e, keyword_init: true)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment