Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'benchmark'
class Hash
def orig_symbolize_keys!
keys.each do |key|
self[(key.to_sym rescue key) || key] = delete(key)
end
self
end
def symbolize_keys!
keys.each do |key|
self[(key.to_sym rescue key)] = delete(key) if key.respond_to?(:to_sym) && !key.is_a?(Fixnum)
end
self
end
end
HASH1 = { 'a' => :a, nil => nil, :b => :b, 1 => 1, [] => [] }
HASH2 = { 'a' => :a, :b => :b, 1 => 1, [] => [] }
STR_HASH = { 'string1' => 'a', 'string2' => 'b', 'string3' => 'c', 'string4' => 'd' }
TESTS = 100_000
Benchmark.bmbm do |results|
results.report("Hash#orig_symbolize_keys! , nil key") { TESTS.times { HASH1.orig_symbolize_keys! } }
results.report("Hash#symbolize_keys! , nil key") { TESTS.times { HASH1.symbolize_keys! } }
results.report("Hash#orig_symbolize_keys!") { TESTS.times { HASH2.orig_symbolize_keys! } }
results.report("Hash#symbolize_keys!") { TESTS.times { HASH2.symbolize_keys! } }
results.report("Hash#orig_symbolize_keys!, string keys") { TESTS.times { STR_HASH.orig_symbolize_keys! } }
results.report("Hash#symbolize_keys!, string keys") { TESTS.times { STR_HASH.symbolize_keys! } }
end
methodmissing:~ lourens$ ruby hash_bench.rb
Rehearsal -----------------------------------------------------------------------
Hash#orig_symbolize_keys! , nil key 3.510000 0.170000 3.680000 ( 3.720439)
Hash#symbolize_keys! , nil key 0.360000 0.000000 0.360000 ( 0.392987)
Hash#orig_symbolize_keys! 2.020000 0.080000 2.100000 ( 2.168747)
Hash#symbolize_keys! 0.360000 0.010000 0.370000 ( 0.371135)
-------------------------------------------------------------- total: 6.510000sec
user system total real
Hash#orig_symbolize_keys! , nil key 3.390000 0.160000 3.550000 ( 3.551547)
Hash#symbolize_keys! , nil key 0.350000 0.000000 0.350000 ( 0.361843)
Hash#orig_symbolize_keys! 3.400000 0.160000 3.560000 ( 3.571425)
Hash#symbolize_keys! 0.360000 0.000000 0.360000 ( 0.362906)
From b57634fcbdab7526965a0b05b39f55ef76451cc5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Lourens=20Naud=C3=A9?= <lourens@methodmissing.com>
Date: Sun, 7 Feb 2010 23:20:37 +0000
Subject: [PATCH] Hash#symbolize_keys(!) optimizations
---
.../lib/active_support/core_ext/hash/keys.rb | 2 +-
1 files changed, 1 insertions(+), 1 deletions(-)
diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb
index 045a694..62990f7 100644
--- a/activesupport/lib/active_support/core_ext/hash/keys.rb
+++ b/activesupport/lib/active_support/core_ext/hash/keys.rb
@@ -22,7 +22,7 @@ class Hash
# to +to_sym+.
def symbolize_keys!
keys.each do |key|
- self[(key.to_sym rescue key) || key] = delete(key)
+ self[key.to_sym] = delete(key) if key.respond_to?(:to_sym)
end
self
end
--
1.6.4.4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment