Navigation Menu

Skip to content

Commit

Permalink
Speed up String#capitalize by using String#escape
Browse files Browse the repository at this point in the history
  • Loading branch information
Evan Phoenix committed Feb 12, 2010
1 parent 38145d6 commit af2e84c
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 22 deletions.
6 changes: 6 additions & 0 deletions kernel/common/bytearray.rb
Expand Up @@ -22,5 +22,11 @@ def inspect
def <=>(other)
compare_bytes(other, size, other.size)
end

# Sets the first character to be an ASCII capitalize letter
# if it's an ASCII lower case letter
def first_capitalize!
self[0] = self[0].toupper
end
end
end
36 changes: 14 additions & 22 deletions kernel/common/string.rb
Expand Up @@ -373,7 +373,15 @@ def []=(*args)
# "HELLO".capitalize #=> "Hello"
# "123ABC".capitalize #=> "123abc"
def capitalize
(str = self.dup).capitalize! || str
return dup if @num_bytes == 0

str = escape(CType::Lowered, true)
str = self.class.new(str) unless instance_of?(String)

str.modify!
str.data.first_capitalize!

return str
end

# Modifies <i>self</i> by converting the first character to uppercase and the
Expand All @@ -385,29 +393,13 @@ def capitalize
# a #=> "Hello"
# a.capitalize! #=> nil
def capitalize!
self.modify!

return if @num_bytes == 0

modified = false

c = @data[0]
if c.islower
@data[0] = c.toupper
modified = true
end
Ruby.check_frozen

i = 1
while i < @num_bytes
c = @data[i]
if c.isupper
@data[i] = c.tolower
modified = true
end
i += 1
end
cap = capitalize()
return nil if cap == self

modified ? self : nil
replace(cap)
return self
end

# Case-insensitive version of <code>String#<=></code>.
Expand Down
8 changes: 8 additions & 0 deletions kernel/delta/ctype.rb
Expand Up @@ -35,4 +35,12 @@ def self.toprint(num)
def toprint
Printed[self]
end

Lowered = Rubinius::Tuple.new 256

i = 0
while i < 256
Lowered[i] = i.tolower.chr
i += 1
end
end

0 comments on commit af2e84c

Please sign in to comment.