Skip to content

Instantly share code, notes, and snippets.

@a2ikm
Last active February 17, 2017 14:06
Show Gist options
  • Save a2ikm/abe7c67e2f329604e6a5ea33d6927c77 to your computer and use it in GitHub Desktop.
Save a2ikm/abe7c67e2f329604e6a5ea33d6927c77 to your computer and use it in GitHub Desktop.
Struct vs Hash initialized from Arrays
require "benchmark"
fields = [:f1, :f2, :f3, :f4, :f5, :f6]
struct = Struct.new("Something", *fields)
values_array = 10_000.times.map {
[rand(10000), rand(10000), rand(10000), rand(10000), rand(10000), rand(10000)]
}
Benchmark.bm(10) do |x|
x.report("Hash") do
values_array.each do |values|
Hash[fields.zip(values)]
end
end
x.report("Struct") do
values_array.each do |values|
struct.new(*values)
end
end
end
$ ruby benchmark.rb
user system total real
Hash 0.030000 0.000000 0.030000 ( 0.028927)
Struct 0.000000 0.000000 0.000000 ( 0.005513)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment