Last active
February 17, 2017 14:06
-
-
Save a2ikm/abe7c67e2f329604e6a5ea33d6927c77 to your computer and use it in GitHub Desktop.
Struct vs Hash initialized from Arrays
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 "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 |
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
$ 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