Skip to content

Commit

Permalink
Optimize normalize_flat_keys
Browse files Browse the repository at this point in the history
I18n::Backend::Flatten.normalize_flat_keys :en, :home, [:country, :county, :second], '|'

Calculating -------------------------------------
            original     1.060k memsize (     0.000  retained)
                        21.000  objects (     0.000  retained)
                         7.000  strings (     0.000  retained)
               patch   652.000  memsize (     0.000  retained)
                        14.000  objects (     0.000  retained)
                         7.000  strings (     0.000  retained)

Comparison:
               patch:        652 allocated
            original:       1060 allocated - 1.63x more

Warming up --------------------------------------
            original    15.765k i/100ms
               patch    18.043k i/100ms
Calculating -------------------------------------
            original    156.733k (± 3.5%) i/s -    788.250k in   5.036161s
               patch    180.959k (± 1.9%) i/s -    920.193k in   5.086948s

Comparison:
               patch:   180959.0 i/s
            original:   156733.1 i/s - 1.15x  (± 0.00) slower
  • Loading branch information
krzysiek1507 committed May 23, 2020
1 parent 14f7792 commit 4031429
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions lib/i18n/backend/flatten.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,17 @@ module Flatten
# and creates way less objects than the one at I18n.normalize_keys.
# It also handles escaping the translation keys.
def self.normalize_flat_keys(locale, key, scope, separator)
keys = [scope, key].flatten.compact
keys = [scope, key]
keys.flatten!
keys.compact!

separator ||= I18n.default_separator

if separator != FLATTEN_SEPARATOR
keys.map! do |k|
k.to_s.tr("#{FLATTEN_SEPARATOR}#{separator}",
"#{SEPARATOR_ESCAPE_CHAR}#{FLATTEN_SEPARATOR}")
end
from_str = "#{FLATTEN_SEPARATOR}#{separator}"
to_str = "#{SEPARATOR_ESCAPE_CHAR}#{FLATTEN_SEPARATOR}"

keys.map! { |k| k.to_s.tr from_str, to_str }
end

keys.join(".")
Expand Down

0 comments on commit 4031429

Please sign in to comment.