Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save doha99-eh/bfcd9e073c03c403ff7fe1e9315d1ca5 to your computer and use it in GitHub Desktop.
Save doha99-eh/bfcd9e073c03c403ff7fe1e9315d1ca5 to your computer and use it in GitHub Desktop.
bm__JSON.parse_HWIA_deep_symbolize_keys_symbolized_name
# frozen_string_literal: true
# gem install benchmark-memory
# gem install benchmark-ips
require 'benchmark/ips'
require 'benchmark/memory'
require 'active_support/all'
TIMES = 50_000
HASH = {
"colour" => "red",
"sizes" => [
"measurements_1" => {
"height" => 1,
"length" => 2,
"depth" => 3,
"specs" => {
"oval" => true,
"patterns" => "french lily"
}
},
"measurements_2" => {
"height" => 10,
"length" => 20,
"depth" => 30,
}
]
}.to_json
Benchmark.ips do |x|
x.config(:time => 5, :warmup => 2)
x.report("with_indifferent_access:") { JSON.parse(HASH).with_indifferent_access[:sizes][0][:measurements_1][:specs] }
x.report("deep_symbolize_keys:") { JSON.parse(HASH).deep_symbolize_keys[:sizes][0][:measurements_1][:specs] }
x.report("symbolize_names:") { JSON.parse(HASH, symbolize_names: true)[:sizes][0][:measurements_1][:specs] }
x.compare!
end
# Warming up --------------------------------------
# with_indifferent_access:
# 7.030k i/100ms
# deep_symbolize_keys: 7.100k i/100ms
# symbolize_names: 17.229k i/100ms
# Calculating -------------------------------------
# with_indifferent_access:
# 67.537k (± 5.2%) i/s - 337.440k in 5.010073s
# deep_symbolize_keys: 79.691k (± 3.6%) i/s - 404.700k in 5.085082s
# symbolize_names: 166.636k (± 8.6%) i/s - 826.992k in 5.037052s
# Comparison:
# symbolize_names:: 166635.5 i/s
# deep_symbolize_keys:: 79691.3 i/s - 2.09x (± 0.00) slower
# with_indifferent_access:: 67537.1 i/s - 2.47x (± 0.00) slower
Benchmark.memory do |x|
x.report("with_indifferent_access:") { JSON.parse(HASH).with_indifferent_access[:sizes][0][:measurements_1][:specs] }
x.report("deep_symbolize_keys:") { JSON.parse(HASH).deep_symbolize_keys[:sizes][0][:measurements_1][:specs] }
x.report("symbolize_names:") { JSON.parse(HASH, symbolize_names: true)[:sizes][0][:measurements_1][:specs] }
x.compare!
end
# Calculating -------------------------------------
# with_indifferent_access:
# 4.960k memsize ( 504.000 retained)
# 38.000 objects ( 3.000 retained)
# 12.000 strings ( 1.000 retained)
# deep_symbolize_keys: 5.640k memsize ( 1.280k retained)
# 55.000 objects ( 8.000 retained)
# 12.000 strings ( 2.000 retained)
# symbolize_names: 4.152k memsize ( 0.000 retained)
# 37.000 objects ( 0.000 retained)
# 12.000 strings ( 0.000 retained)
# Comparison:
# symbolize_names:: 4152 allocated
# with_indifferent_access:: 4960 allocated - 1.19x more
# deep_symbolize_keys:: 5640 allocated - 1.36x more
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment