Repository navigation
Conversation
|
r? @maxdexh rustbot has assigned @maxdexh. Use Why was this reviewer chosen?The reviewer was selected based on:
|
char::encode_utf8_raw_unchecked over ptr::copyString::retain implementation to use char::encode_utf8_raw_unchecked over ptr::copy
|
cc @joboet (reviewer of the reverted PR) |
|
Thank you for preparing this. It looks like this PR:
In general a "straight revert" is preferable in these situations, especially for reverts we might want to backport, as that's usually less risky and quicker to review. See also the section on reverts in the forge (technically compiler team policy, but a lot of it is good advice more generally). So I'd propose that you (or someone else, if you'd prefer) first create a straight revert (with only minimal changes to fix conflicts), we backport that, and any other changes (including e.g. |
|
I would be open to reverting the implementation of let ch =
// SAFETY: `guard.idx` is positive-or-zero and less that len so the `get_unchecked`
// is in bound. `self` is valid UTF-8 like string and the returned slice starts at
// a unicode code point so the `Chars` always return one character.
unsafe { guard.s.get_unchecked(guard.idx..len).chars().next().unwrap_unchecked() };(same piece of code seen in #150067 just with to this: // SAFETY: Use `vec`: `String`'s deref includes `write..read`,
// which may be invalid UTF-8. The vector's length is still `len`;
// `read < len`, so `read..len` is in bounds and non-empty.
// At least one character was removed, so `write < read`.
// Copies end before the next `read`, preserving unread bytes.
// `read` starts after a `char_indices` character and advances by whole
// characters, so it stays on a char boundary. The original string was valid UTF-8,
// so the unchanged, non-empty tail is valid UTF-8 and `chars().next()` returns `Some`.
let ch = unsafe {
let tail = str::from_utf8_unchecked(g.s.vec.get_unchecked(read..len));
tail.chars().next().unwrap_unchecked()
};I believe the reason why this change was made was because it's possible for our string to contain invalid utf 8 bytes at one point in replacing 'deleted' bytes/'holes' (e.g. the example provided in #163624, shows that when we remove Regardless, I wanted to check in on if I should integrate the change made in #163624 to the |
String::retain implementation to use char::encode_utf8_raw_unchecked over ptr::copychar::encode_utf8_raw_unchecked over ptr::copy in String::retain
|
@asder8215 If reverting that other PR immediately gets us to a fully clean revert: Yes, both. It will collapse any waffling on our side into a "yes". Please try and inform. If that lands and gets backported, then we want to immediately reland a variant of #163624 so that the safety hygiene changes are addressed. They don't necessarily affect the "amount of actual UB" in the code, as I understand it, but they do affect how brittle it is to further changes in our codebase so they remain desirable. |
|
To answer this question (and expand on what Jubilee said w.r.t. safety hygiene):
Unless explicitly stated otherwise, functions that take Code inside the standard library can rely on more details than we publicly guarantee, but this sets a bad example and is harder to maintain (e.g., when making changes to one function you usually don't audit all callers to see what implementation details they rely on). So it's better to not call |
|
Just noting it in here: I was benchmarking the The current string retain refers to the fereidani's It really seems like swapping out the |
| } | ||
|
|
||
| impl Drop for PanicGuard<'_> { | ||
| #[cold] |
There was a problem hiding this comment.
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.
| #[inline] | ||
| #[must_use = "`self` will be dropped if the result is not used"] | ||
| #[stable(feature = "string_into_chars", since = "1.101.0")] | ||
| #[stable(feature = "string_into_chars", since = "CURRENT_RUSTC_VERSION")] |
There was a problem hiding this comment.
I also have no idea why these changes were made. I don't recall making these myself.
There was a problem hiding this comment.
git works in mysterious ways ✨
This comment has been minimized.
This comment has been minimized.
| let ptr = g.s.vec.as_mut_ptr(); | ||
| ptr::copy(ptr.add(read), ptr.add(g.write), ch_len); | ||
| } | ||
| core::char::encode_utf8_raw_unchecked(ch as u32, g.s.as_mut_ptr().add(g.write)); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@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.
Slice the byte vector before converting to str, avoiding a whole-buffer conversion while compaction may leave invalid UTF-8.
…g::retain` Using `char::encode_utf8_raw_unchecked` significantly improves the performance (and fixes regression) of `String::retain` over using `ptr::copy(src, dst, ch_len)`
546d7ab to
ef992ba
Compare
|
Currently, I have Feiradani's and Talha's changes in separate commits. If it's preferred to squash the commits and point to Fereidani's and Talha's PR in the commit message directly, lmk and I could do that. |
|
Separate commits is fine. |
|
I didn't follow the discussion here at all, and the wall of PR links (that isn't even complete) kinda confuses me. @workingjubilee do you want to take this? You seem to know more about this method |
Related to #165988
This PR re-introduces the re-implementation of
String::retainmade in #150067 and the safety hygiene changes made in #163624.The re-implementation of
String::retainwas initially reverted due to a performance regression found from theptr::copy(...)code in #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):rust/library/core/src/char/methods.rs
Lines 2615 to 2648 in 5f4effd
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