Browse files

Speed up I18n.normalize_keys by caching reused normalizations and pro…

…ducing less garbage.

===> SimpleBackend (1000 translations)
                           BEFORE                 AFTER
store               723.09 ms 1661412 obj  720.83 ms 1638428 objects
t (depth=3)          42.95 ms   73009 obj   29.73 ms   42029 objects
t (depth=5)          53.73 ms   87009 obj   34.62 ms   50035 objects
t (depth=7)          62.42 ms  101009 obj   39.86 ms   58041 objects
t w/ default         93.45 ms   86009 obj   37.13 ms   54030 objects
t w/ interpolation   99.65 ms  150009 obj   80.79 ms  112035 objects
t subtree            41.68 ms   72009 obj   28.87 ms   41009 objects

Similar improvement for InterpolationBackend. FastBackend unaffected.
  • Loading branch information...
1 parent 9c3a571 commit 819dac0fea9c29e6545801aa107e63e355728cd4 @jeremy jeremy committed with Apr 17, 2010
Showing with 29 additions and 4 deletions.
  1. +29 −4 lib/i18n.rb
View
33 lib/i18n.rb
@@ -256,10 +256,10 @@ def localize(object, options = {})
# Splits keys that contain dots into multiple keys. Makes sure all
# keys are Symbols.
def normalize_keys(locale, key, scope, separator = nil)
- keys = [locale] + Array(scope) + Array(key)
- keys = keys.map { |k| k.to_s.split(separator || I18n.default_separator) }
- keys = keys.flatten - ['']
- keys.map { |k| k.to_sym }
+ separator ||= I18n.default_separator
+ normalize_key(locale, separator) +
+ normalize_key(scope, separator) +
+ normalize_key(key, separator)
end
# making these private until Ruby 1.9.2 can send to protected methods again
@@ -306,5 +306,30 @@ def handle_exception(exception, locale, key, options)
def normalize_translation_keys(locale, key, scope, separator = nil)
normalize_keys(locale, key, scope, separator)
end
+
+ def normalize_key(key, separator)
+ normalized_key_cache(separator)[key] ||=
+ case key
+ when Array
+ key.map { |k| normalize_key(k, separator) }.flatten
+ when nil
+ []
+ else
+ key = key.to_s
+ if key == ''
+ []
+ elsif key.include?(separator)
+ keys = key.split(separator) - ['']
+ keys.map { |k| k.to_sym }
+ else
+ [key.to_sym]
+ end
+ end
+ end
+
+ def normalized_key_cache(separator)
+ @normalized_key_cache ||= Hash.new { |h,k| h[k] = {} }
+ @normalized_key_cache[separator]
+ end
end
end

0 comments on commit 819dac0

Please sign in to comment.