Open
Description
Motivation
This function reserves some space during the allocation of Vec v
and then pushs ASCII characters into the Vec.
And I notice that
- The length of
v
is strictly bounded by a fixed number (larger than the existing one).
We can reset the space reserved to a proper value and manipulate the pointer ofv
directly. - The return value, a
String
, is constructed by ASCII characters.
We can useString::from_utf8_unchecked
to skip the unnecessary checking.
A draft PR can be found at PR#1848.
Safety
- I add comments in the source code to explain its safety.
- I test the optimized code with the existing safe implementation. The result shows that they generate similar outputs.
Effectiveness
I also write a simple benchmark to examine the effectiveness of this optimization. The result is shown as below.
c.bench_function("bench_to_hex", |b| {
b.iter(|| {
b"0123456789abcdefghijklmnopqrstuvwxyz".to_hex(3);
});
});
existing implementation
bench_to_vec time: [1.0756 µs 1.0836 µs 1.0935 µs]
Found 6 outliers among 100 measurements (6.00%)
3 (3.00%) high mild
3 (3.00%) high severe
optimized implementation
bench_to_vec time: [747.10 ns 757.98 ns 771.13 ns]
change: [-31.861% -30.500% -29.129%] (p = 0.00 < 0.05)
Performance has improved.
Found 8 outliers among 100 measurements (8.00%)
4 (4.00%) high mild
4 (4.00%) high severe
Metadata
Metadata
Assignees
Labels
No labels