From caf57c2656e6b18fce43e132848f418f3c672a10 Mon Sep 17 00:00:00 2001 From: Quinton Miller Date: Sun, 10 Nov 2024 20:05:54 +0800 Subject: [PATCH] Optimize `String#rchop?()` (#15175) 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. --- src/string.cr | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/string.cr b/src/string.cr index 09272c80eb45..273472d34517 100644 --- a/src/string.cr +++ b/src/string.cr @@ -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`.