-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Closed as not planned
Milestone
Description
When the string consists of only ASCII characters, we can convert lower case to upper case using bitwise operators. Bitwise operators are more efficient than using addition or subtraction.
Lines 616 to 625 in 3e67f46
| for i := 0; i < len(s); i++ { | |
| c := s[i] | |
| if 'a' <= c && c <= 'z' { | |
| c -= 'a' - 'A' | |
| if pos < i { | |
| b.WriteString(s[pos:i]) | |
| } | |
| b.WriteByte(c) | |
| pos = i + 1 | |
| } |
For example, in Rust, they used bitwise operator to implement the converter.
I propose that we replace the addition and subtraction operators with bitwise operators in the following four places.
Lines 616 to 625 in 3e67f46
| for i := 0; i < len(s); i++ { | |
| c := s[i] | |
| if 'a' <= c && c <= 'z' { | |
| c -= 'a' - 'A' | |
| if pos < i { | |
| b.WriteString(s[pos:i]) | |
| } | |
| b.WriteByte(c) | |
| pos = i + 1 | |
| } |
Lines 656 to 666 in 3e67f46
| for i := 0; i < len(s); i++ { | |
| c := s[i] | |
| if 'A' <= c && c <= 'Z' { | |
| c += 'a' - 'A' | |
| if pos < i { | |
| b.WriteString(s[pos:i]) | |
| } | |
| b.WriteByte(c) | |
| pos = i + 1 | |
| } | |
| } |
Lines 638 to 652 in 3e67f46
| if isASCII { // optimize for ASCII-only byte slices. | |
| if !hasLower { | |
| // Just return a copy. | |
| return append([]byte(""), s...) | |
| } | |
| b := bytealg.MakeNoZero(len(s)) | |
| for i := 0; i < len(s); i++ { | |
| c := s[i] | |
| if 'a' <= c && c <= 'z' { | |
| c -= 'a' - 'A' | |
| } | |
| b[i] = c | |
| } | |
| return b | |
| } |
Lines 669 to 682 in 3e67f46
| if isASCII { // optimize for ASCII-only byte slices. | |
| if !hasUpper { | |
| return append([]byte(""), s...) | |
| } | |
| b := bytealg.MakeNoZero(len(s)) | |
| for i := 0; i < len(s); i++ { | |
| c := s[i] | |
| if 'A' <= c && c <= 'Z' { | |
| c += 'a' - 'A' | |
| } | |
| b[i] = c | |
| } | |
| return b | |
| } |
Reactions are currently unavailable