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, [] => [] }
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! } }
end
From eaad3a8ad25fbea9c6e8c252ac304f57a9e8c53e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Lourens=20Naud=C3=A9?= <lourens@methodmissing.com>
Date: Mon, 8 Feb 2010 00:05:33 +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..e4d429f 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 rescue key)] = delete(key) if key.respond_to?(:to_sym) && !key.is_a?(Fixnum)
end
self
end
--
1.6.4.4
methodmissing:~ lourens$ ruby hash_bench.rb
Rehearsal -----------------------------------------------------------------------
Hash#orig_symbolize_keys! , nil key 3.500000 0.160000 3.660000 ( 3.686203)
Hash#symbolize_keys! , nil key 0.510000 0.000000 0.510000 ( 0.506390)
Hash#orig_symbolize_keys! 2.000000 0.090000 2.090000 ( 2.096217)
Hash#symbolize_keys! 0.470000 0.000000 0.470000 ( 0.468481)
-------------------------------------------------------------- total: 6.730000sec
user system total real
Hash#orig_symbolize_keys! , nil key 3.520000 0.160000 3.680000 ( 3.753897)
Hash#symbolize_keys! , nil key 0.510000 0.000000 0.510000 ( 0.513103)
Hash#orig_symbolize_keys! 2.020000 0.090000 2.110000 ( 2.115938)
Hash#symbolize_keys! 0.470000 0.000000 0.470000 ( 0.481901)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment