rust-decimal icon indicating copy to clipboard operation
rust-decimal copied to clipboard

Allow the usage of stack-based strings

Open c410-f3r opened this issue 2 months ago • 2 comments

ToString::to_string makes a heap allocation and such a thing can cause a negative performance impact if used in a hot path. For example:

fn foo(dec: &mut Decimal) {
  loop {
    // stuff
    let string = dec.to_string();
    // more stuff
  }
}

One of the reasons why serialization was slow was also due to two heap allocations (https://github.com/paupino/rust-decimal/pull/296). Therefore, it would be nice to expose to_str_internal.

The only pseudo-disadvantage is hard coding arrayvec into public interfaces but this can be mitigated in the future with a custom home-made ArrayString that returns ([u8; MAX_STR_BUFFER_SIZE], u8).

c410-f3r avatar Nov 17 '25 21:11 c410-f3r

Maybe I'm misunderstanding the proposal, but to_str_internal is used inside our implementation of std::fmt::Display, so wouldn't write! or similar work here?

Tony-Samuels avatar Nov 17 '25 22:11 Tony-Samuels

The machinery behind formatting stuff is notoriously slow and such a thing also requires an additional copy to the desired container.

https://github.com/rust-lang/rust/issues/10761 https://github.com/rust-lang/rust/issues/76490

One of the reasons is the internal use of dynamic dispatch, see https://blog.m-ou.se/format-args.

I didn't profile Display but a direct exposure of the underlying array will likely be faster than write!.

c410-f3r avatar Nov 17 '25 23:11 c410-f3r