Permalink
Browse files

Reduce memory usage slightly in String#parameterize

[#1034 state:committed]
  • Loading branch information...
1 parent a4629e7 commit 5556db22c57294a9f4e2ee4e633834ec6a200242 @NZKoz NZKoz committed Oct 7, 2008
Showing with 9 additions and 5 deletions.
  1. +9 −5 activesupport/lib/active_support/inflector.rb
@@ -259,11 +259,15 @@ def demodulize(class_name_in_module)
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
def parameterize(string, sep = '-')
re_sep = Regexp.escape(sep)
- transliterate(string).
- gsub(/[^a-z0-9\-_\+]+/i, sep). # Turn unwanted chars into the separator.
- squeeze(sep). # No more than one of the separator in a row.
- gsub(/^#{re_sep}|#{re_sep}$/i, ''). # Remove leading/trailing separator.
- downcase
+ # replace accented chars with ther ascii equivalents
@dasch

dasch Oct 7, 2008

Contributor

Should have read # Replace accented chars with their ASCII equivalents.

+ parameterized_string = transliterate(string)
+ # Turn unwanted chars into the seperator
@dasch

dasch Oct 7, 2008

Contributor

Needs a dot at the end.

+ parameterized_string.gsub!(/[^a-z0-9\-_\+]+/i, sep)
+ # No more than one of the separator in a row.
+ parameterized_string.squeeze!(sep)
+ # Remove leading/trailing separator.
+ parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
+ parameterized_string.downcase
end

6 comments on commit 5556db2

Contributor

xaviershay replied Oct 7, 2008


GC.disable

def count_string_objects_created
  start = ObjectSpace.each_object(String) {}
  yield
  (ObjectSpace.each_object(String) {} - start).to_s
end

puts '#downcase:  ' + count_string_objects_created {
  a = "hello"
  a.downcase
}

puts '#downcase!: ' + count_string_objects_created {
  a = "hello"
  a.downcase!
}
Contributor

xaviershay replied Oct 7, 2008

you know, if you’re really trying to get it down. downcase! returns the value, too:
>> "A".downcase! => "a"

ripta replied Oct 7, 2008

downcase! returns nil if the method doesn’t change the string.


>> a = "hello"
=> "hello"
>> a.downcase
=> "hello"
>> a.downcase!
=> nil

Nonetheless, it does create one less object every time.

ripta replied Oct 7, 2008

Ah, man, I really wish I had a preview button.

Contributor

xaviershay replied Oct 7, 2008

oh fair point


parameterized_string.downcase!
parameterized_string
Member

NZKoz replied Oct 8, 2008

I was just merging rick’s attachment_fu differences, it’s minor garbage enhancements but no huge deal, don’t overthink it guys :)

Please sign in to comment.