Skip to content

Instantly share code, notes, and snippets.

@groyoh
Last active May 23, 2016 07:23
Show Gist options
  • Save groyoh/ac635603c889e31765e9b510e10100f8 to your computer and use it in GitHub Desktop.
Save groyoh/ac635603c889e31765e9b510e10100f8 to your computer and use it in GitHub Desktop.
BSON::Document + symbols VS #to_h + strings
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem "bson"
gem "benchmark-ips"
end
SYMBOLS = [:a, :b, :c, :d, :e, :f, :g, :h, :i].freeze
STRINGS = ["a", "b", "c", "d", "e", "f", "g", "h", "i"].freeze
STRINGS.each(&:freeze)
DOC = BSON::Document.new(
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 4,
"e" => 5,
"f" => 6,
"g" => 7,
"h" => 8,
"i" => 9
).freeze
GC.start
GC.disable
Benchmark.ips do |x|
x.report("BSON document") do
SYMBOLS.each do |s|
DOC[s]
end
end
x.report("Hash") do
doc = DOC.to_h
STRINGS.each do |s|
doc[s]
end
end
x.compare!
end
__END__
Warming up --------------------------------------
BSON document 45.712k i/100ms
Hash 62.576k i/100ms
Calculating -------------------------------------
BSON document 580.713k (± 3.6%) i/s - 2.926M in 5.044795s
Hash 845.759k (± 4.3%) i/s - 4.255M in 5.041228s
Comparison:
Hash: 845759.2 i/s
BSON document: 580713.4 i/s - 1.46x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment