1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Decrease allocations in transliterate

We can save a few objects by freezing the `replacement` string. We save a few more by down-casing the string in memory instead of allocating a new one. We save far more objects by checking for the default separator `"-"`, and using pre-generated regular expressions.

We will save 209,231 bytes and 1,322 objects.
This commit is contained in:
schneems 2015-07-26 13:59:12 -05:00
parent 1993e2ccbd
commit 57ba9cbc6c

View file

@ -58,7 +58,7 @@ module ActiveSupport
# I18n.locale = :de # I18n.locale = :de
# transliterate('Jürgen') # transliterate('Jürgen')
# # => "Juergen" # # => "Juergen"
def transliterate(string, replacement = "?") def transliterate(string, replacement = "?".freeze)
I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize( I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize(
ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c), ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c),
:replacement => replacement) :replacement => replacement)
@ -75,13 +75,21 @@ module ActiveSupport
# Turn unwanted chars into the separator # Turn unwanted chars into the separator
parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep) parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep)
unless sep.nil? || sep.empty? unless sep.nil? || sep.empty?
re_sep = Regexp.escape(sep) if sep == "-".freeze
re_duplicate_seperator = /-{2,}/
re_leading_trailing_separator = /^-|-$/i
else
re_sep = Regexp.escape(sep)
re_duplicate_seperator = /#{re_sep}{2,}/
re_leading_trailing_separator = /^#{re_sep}|#{re_sep}$/i
end
# No more than one of the separator in a row. # No more than one of the separator in a row.
parameterized_string.gsub!(/#{re_sep}{2,}/, sep) parameterized_string.gsub!(re_duplicate_seperator, sep)
# Remove leading/trailing separator. # Remove leading/trailing separator.
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, ''.freeze) parameterized_string.gsub!(re_leading_trailing_separator, ''.freeze)
end end
parameterized_string.downcase parameterized_string.downcase!
parameterized_string
end end
end end
end end