Skip to content

Use unsafe APIs to optimize HexDisplay::to_hex_from #1847

@Unparalleled-Calvin

Description

@Unparalleled-Calvin

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 of v directly.
  • The return value, a String, is constructed by ASCII characters.
    We can use String::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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions