Skip to content

Instantly share code, notes, and snippets.

@methodmissing
Created February 7, 2010 23:13
Show Gist options
  • Save methodmissing/297750 to your computer and use it in GitHub Desktop.
Save methodmissing/297750 to your computer and use it in GitHub Desktop.
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 if key.respond_to?(:to_sym)) || key] = delete(key)
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 ef206f879b5bdae312847a256a987135cd2d4b73 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Lourens=20Naud=C3=A9?= <[email protected]>
Date: Sun, 7 Feb 2010 22:48:21 +0000
Subject: [PATCH] Faster Hash#symbolize_keys!
---
.../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..62b38fb 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 if key.respond_to?(:to_sym)) || key] = delete(key)
end
self
end
--
1.6.4.4
methodmissing:~ lourens$ ruby hash_bench.rb
Rehearsal -----------------------------------------------------------------------
Hash#orig_symbolize_keys! , nil key 3.510000 0.160000 3.670000 ( 3.717758)
Hash#symbolize_keys! , nil key 0.690000 0.000000 0.690000 ( 0.727905)
Hash#orig_symbolize_keys! 2.020000 0.090000 2.110000 ( 2.103823)
Hash#symbolize_keys! 0.580000 0.000000 0.580000 ( 0.589944)
-------------------------------------------------------------- total: 7.050000sec
user system total real
Hash#orig_symbolize_keys! , nil key 3.490000 0.160000 3.650000 ( 3.668927)
Hash#symbolize_keys! , nil key 0.690000 0.000000 0.690000 ( 0.691079)
Hash#orig_symbolize_keys! 2.020000 0.080000 2.100000 ( 2.125950)
Hash#symbolize_keys! 0.600000 0.000000 0.600000 ( 0.625422)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment