Skip to content

Commit

Permalink
Optimize String#rchop?() (#15175)
Browse files Browse the repository at this point in the history
This is similar to #15153.

* Uses `Char::Reader` to read backwards from the end of the string. This does not require decoding the whole string, unlike calculating `size - 1`.
* If the current string does not end with an ASCII character and its size is unknown, `#single_byte_optimizable?` traverses the entire string. This is no longer unnecessary because the above handles everything already.
* If the current string's size is known, the new string's size can be derived from it.
  • Loading branch information
HertzDevil authored Nov 10, 2024
1 parent 0620da4 commit caf57c2
Showing 1 changed file with 1 addition and 5 deletions.
6 changes: 1 addition & 5 deletions src/string.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1798,11 +1798,7 @@ class String
def rchop? : String?
return if empty?

if to_unsafe[bytesize - 1] < 0x80 || single_byte_optimizable?
return unsafe_byte_slice_string(0, bytesize - 1)
end

self[0, size - 1]
unsafe_byte_slice_string(0, Char::Reader.new(at_end: self).pos, @length > 0 ? @length - 1 : 0)
end

# Returns a new `String` with *suffix* removed from the end of the string if possible, else returns `nil`.
Expand Down

0 comments on commit caf57c2

Please sign in to comment.