Created
October 9, 2024 17:00
-
-
Save fractaledmind/fc8987246036d60d4e5fb47f8cc4f916 to your computer and use it in GitHub Desktop.
Ruby benchmark script to test which way is faster to normalize a hash: stringify_keys! or symbolize_keys!
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' | |
require 'active_support/core_ext/hash/keys' | |
def create_mixed_hash(size) | |
hash = {} | |
size.times do |i| | |
if i.even? | |
hash[i.to_s] = "value#{i}" | |
else | |
hash[i.to_s.to_sym] = "value#{i}" | |
end | |
end | |
hash | |
end | |
def run_benchmark(size) | |
mixed_hash = create_mixed_hash(size) | |
Benchmark.bm(20) do |x| | |
x.report("symbolize_keys!:") { mixed_hash.dup.symbolize_keys! } | |
x.report("stringify_keys!:") { mixed_hash.dup.stringify_keys! } | |
end | |
end | |
puts "Benchmark for small hash (100 elements):" | |
run_benchmark(100) | |
puts "\nBenchmark for medium hash (10,000 elements):" | |
run_benchmark(10_000) | |
puts "\nBenchmark for large hash (100,000 elements):" | |
run_benchmark(100_000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment