Use `char::encode_utf8_raw_unchecked` over `ptr::copy` in `String::retain` #165992
I have to update this safety comment, to say it's behind the read in character ch by at least ch_len (g.read is updated at the end of the loop).
Will do this later in the morning.
Also, noting for myself this should be removed when I rebase after revert gets merged in. Earlier, I thought we're not entering this case often if it's similar to Vec::retain where we set the length of the vec and mem::forget the guard, but we call drop(g) at the end.
I also have no idea why these changes were made. I don't recall making these myself.
git works in mysterious ways :sparkles:
Now that I look at things properly since the revert is landed and we have more room to think about this, I believe the code that you suggested is very similar to the contents of encode_utf8_raw_unchecked, @fereidani.
I remember that I had benchmark this in the original PR and as it is recalculating the utf8 length once more it was slower,
Following is the strongest solution that I've found then:
unsafe {
let src = ptr.add(read);
let dst = ptr.add(g.write);
match ch_len {
1 => ptr::copy(src, dst, 1),
2 => ptr::copy(src, dst, 2),
3 => ptr::copy(src, dst, 3),
_ => ptr::copy(src, dst, 4),
}
}
We already have the ch_len available, there is no good reason to recalculate it.
I also remember that instruction count was smaller for the code above. But I'll suggest contributor to do their own benchmarks and instruction count comparisons with the current version of rust compiler.
@fereidani I tried out your suggestion in a separate benchmark file here on the same benchmark case. Running cargo bench --no-run and perf stat <benchmark executable> --bench gives me the following results (also can be found in this folder, where version 1 refers to char::encode_utf8_raw_unchecked change and version 2 refers to your change):
This is the char::encode_utf8_raw_unchecked results:
Optimized String Retain Benchmarks
time: [24.037 µs 24.050 µs 24.064 µs]
change: [−0.1407% +0.2229% +0.4890%] (p = 0.18 > 0.05)
No change in performance detected.
Found 12 outliers among 100 measurements (12.00%)
9 (9.00%) low mild
2 (2.00%) high mild
1 (1.00%) high severe
Performance counter stats for './target/release/build/string_retain_bench/c2239f57c8c677a2/out/optimized_string_retain_bench-c2239f57c8c677a2 --bench':
0 context-switches:u # 0.0 cs/sec cs_per_second
0 cpu-migrations:u # 0.0 migrations/sec migrations_per_second
6,221 page-faults:u # 404.3 faults/sec page_faults_per_second
15,386.38 msec task-clock:u # nan CPUs CPUs_utilized
190,798,614 branch-misses:u # 0.4 % branch_miss_rate (49.98%)
53,941,263,358 branches:u # 3505.8 M/sec branch_frequency (50.07%)
70,711,942,238 cpu-cycles:u # 4.6 GHz cycles_frequency (66.76%)
222,588,101,890 instructions:u # 3.1 instructions insn_per_cycle (50.07%)
1,572,526,614 stalled-cycles-frontend:u # 0.02 frontend_cycles_idle (49.97%)
8.640385245 seconds time elapsed
15.110534000 seconds user
0.075471000 seconds sys
This is the ptr::copy(...) suggestion results:
Optimized String Retain Version Two Benchmarks
time: [27.290 µs 27.355 µs 27.438 µs]
change: [+1.0174% +1.1835% +1.3712%] (p = 0.00 < 0.05)
Performance has regressed.
Found 8 outliers among 100 measurements (8.00%)
6 (6.00%) high mild
2 (2.00%) high severe
Performance counter stats for './target/release/build/string_retain_bench/fe2b0b9936d108b4/out/optimized_string_retain_two_bench-fe2b0b9936d108b4 --bench':
0 context-switches:u # 0.0 cs/sec cs_per_second
0 cpu-migrations:u # 0.0 migrations/sec migrations_per_second
6,462 page-faults:u # 408.9 faults/sec page_faults_per_second
15,803.18 msec task-clock:u # nan CPUs CPUs_utilized
193,426,678 branch-misses:u # 0.4 % branch_miss_rate (50.04%)
50,460,848,700 branches:u # 3193.1 M/sec branch_frequency (50.00%)
72,576,877,287 cpu-cycles:u # 4.6 GHz cycles_frequency (66.68%)
218,952,799,755 instructions:u # 3.0 instructions insn_per_cycle (49.97%)
1,558,472,472 stalled-cycles-frontend:u # 0.02 frontend_cycles_idle (50.02%)
9.074109030 seconds time elapsed
15.438428000 seconds user
0.106568000 seconds sys
It's true that your suggestion improves over the previous String::retain implementation (previous to the re-implementation you made I mean). However, it does seem like using char::encode_utf8_raw_unchecked directly is slightly faster than having this match expression on the length of the character according to cargo bench and what perf results are telling me. Instruction counts are higher with char::encode_utf8_raw_unchecked, but it seems like it has less branch-misses, page faults, total cpu-cycles is lower.
JohnTitor
asder8215
Related to https://github.com/rust-lang/rust/issues/165988
This PR re-introduces the re-implementation of
String::retainmade in https://github.com/rust-lang/rust/pull/150067 and the safety hygiene changes made in https://github.com/rust-lang/rust/pull/163624.The re-implementation of
String::retainwas initially reverted due to a performance regression found from theptr::copy(...)code in rust-lang/rust#150067. The previous (or current at this time of writing/editing this description) implementation utilizedchar::encode_utf8to copy over retained bytes into holes/deleted bytes area, which I would assume it's faster than doing aptr::copy(...)as it just copies over the retained character into the destination one by one (we don't have to worry about overlap safety unlike whatptr::copy_nonoverlappingrequires since we utilize a copy ofchar):https://github.com/rust-lang/rust/blob/5f4effd579500175af844241eb179e756190f1e7/library/core/src/char/methods.rs#L2615-L2648
Furthermore, since we don't need the returned mutable string slice from
char::encode_utf8, I usechar::encode_utf8_raw_uncheckeddirectly instead.cc @fereidani @Talha-Dmr
<!-- homu-ignore:start -->
<!--
Please read our [LLM policy] before opening a PR,
If you used an LLM to generate any part of this PR, including the PR description, please disclose that according to our [guidelines][disclosure guidelines].
LLM contributions are not banned, but are held to a higher standard of review and correctness.
[LLM policy]: https://forge.rust-lang.org/policies/llm-usage.html
[disclosure guidelines]: https://rustc-dev-guide.rust-lang.org/llm-guidance/writing.html#disclosure-guidelines
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.
This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using
r? <reviewer name>
When merged, your PR's description becomes part of the commit message of a merge commit.
If you do not want certain parts of it (such as your LLM disclosure) to show up in the permanent git history,
surround them with a pair of HTML comments containing
homu-ignore:startandhomu-ignore:end.-->
<!-- homu-ignore:end -->