Last active
August 29, 2015 14:01
-
-
Save mfpiccolo/9a234d707e19eae32c9d to your computer and use it in GitHub Desktop.
Gives an example of the use case of to struct and benchmarks against OpenStruct.
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 "json" | |
require 'benchmark' | |
require 'bigdecimal/math' | |
class Hash | |
def to_struct | |
Struct.new(*(k = self.keys)).new(*self.values_at(*k)) | |
end | |
end | |
# You have a hash that you have built in your app | |
sample_hash = { | |
foo_key: "foo_val", | |
bar_key: "bar_val", | |
baz_key: "baz_val", | |
} | |
# Then you have JSON coming from some external api | |
json_response = "{\"qux_key\":\"qux_val\",\"quux_key\":\"quux_val\",\"corge_key\":\"corge_val\"}" | |
hash_with_unknown_keys = JSON.parse(json_response) | |
# Merge these two together | |
sample_hash.merge!(hash_with_unknown_keys) | |
iterations = 100_000 | |
Benchmark.bm do |bm| | |
bm.report "#to_struct" do | |
iterations.times do | |
# Would be super nice if I could convert this to a struct with a method | |
# Somehow a bit faster than the explicit example below and much faster than open struct | |
sample_struct = sample_hash.to_struct | |
sample_struct.foo_key | |
end | |
end | |
bm.report "Struct" do | |
iterations.times do | |
sample_struct = Struct.new(:foo_key, :bar_key, :baz_key, :quux_key, :quux_key, :corge_key) | |
.new("foo_val", "bar_val", "baz_val", "qux_val", "quux_val", "corge_val") | |
sample_struct.foo_key | |
end | |
end | |
bm.report "OpenStruct" do | |
iterations.times do | |
sample_open_struct = OpenStruct.new(sample_hash) | |
sample_open_struct.foo_key | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment