diff options
author | schneems <richard.schneeman@gmail.com> | 2015-07-26 13:59:12 -0500 |
---|---|---|
committer | schneems <richard.schneeman@gmail.com> | 2015-07-30 12:31:04 -0500 |
commit | 57ba9cbc6ccaa20a1ac3ca671d17040946839db3 (patch) | |
tree | 7a6bbe0795df3a6407f318a1da0296d86503456f /activesupport | |
parent | 1993e2ccbd7c5651278ea30bdc9d8034f5197945 (diff) | |
download | rails-57ba9cbc6ccaa20a1ac3ca671d17040946839db3.tar.gz rails-57ba9cbc6ccaa20a1ac3ca671d17040946839db3.tar.bz2 rails-57ba9cbc6ccaa20a1ac3ca671d17040946839db3.zip |
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.
Diffstat (limited to 'activesupport')
-rw-r--r-- | activesupport/lib/active_support/inflector/transliterate.rb | 18 |
1 files changed, 13 insertions, 5 deletions
diff --git a/activesupport/lib/active_support/inflector/transliterate.rb b/activesupport/lib/active_support/inflector/transliterate.rb index 2c03956672..7b28eeb6e2 100644 --- a/activesupport/lib/active_support/inflector/transliterate.rb +++ b/activesupport/lib/active_support/inflector/transliterate.rb @@ -58,7 +58,7 @@ module ActiveSupport # I18n.locale = :de # transliterate('Jürgen') # # => "Juergen" - def transliterate(string, replacement = "?") + def transliterate(string, replacement = "?".freeze) I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize( ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c), :replacement => replacement) @@ -75,13 +75,21 @@ module ActiveSupport # Turn unwanted chars into the separator parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep) 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. - parameterized_string.gsub!(/#{re_sep}{2,}/, sep) + parameterized_string.gsub!(re_duplicate_seperator, sep) # Remove leading/trailing separator. - parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, ''.freeze) + parameterized_string.gsub!(re_leading_trailing_separator, ''.freeze) end - parameterized_string.downcase + parameterized_string.downcase! + parameterized_string end end end |