-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Faster reverse() string function for ASCII-only case #14195
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
1010906
to
7e91bc8
Compare
// SAFETY: Since the original string was ASCII, reversing the bytes still results in valid UTF-8. | ||
let reversed = unsafe { | ||
// reverse bytes directly since ASCII characters are single bytes | ||
String::from_utf8_unchecked(s.bytes().rev().collect::<Vec<u8>>()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We could avoid a allocation here by copying into a Vec<u8>
buffer
// slightly faster than using iterator `bytes`
bytes_buf.extend(s.as_bytes())
bytes_buf.reverse()
...
bytes_buf.clear()
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Got an improvement of ~30% at most after add bytes_buf
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice
028333c
to
e8b44b5
Compare
That is some sweet sweet performance |
Thanks @UBarney and @Dandandan |
Which issue does this PR close?
Closes #12445.
Rationale for this change
See the issue.
What changes are included in this PR?
gen_string_array
inbenches/character_length.rs
to helper.rsAre these changes tested?
Yes. Using existing unit test
bench result
Are there any user-facing changes?
No