Skip to content

Investigate to_arraystring performance #1

@dtolnay

Description

@dtolnay

I came across your crate from this comment in the tracking issue of core::fmt::NumBuffer: rust-lang/rust#138215 (comment).

I see that value.to_arraystring().as_str() is effectively just arrayvec::ArrayString::from(itoa::Buffer::new().format(value)).unwrap().as_str():

impl ToArrayString for $type {
const MAX_LENGTH: usize = $len;
type ArrayString = ArrayString<$len>;
#[inline]
fn to_arraystring(self) -> Self::ArrayString {
fmt_int_to_buf(self)
}
}

pub(crate) fn $name<const CAP: usize>(val: impl $lib::$type) -> arrayvec::ArrayString<CAP> {
let mut buffer = $lib::Buffer::new();
let formatted_ref = buffer.format(val);
arrayvec::ArrayString::from(formatted_ref).unwrap()
}

However, something about the fact that the rendered string is relocated 6 times between when it is written and when it is read causes it to optimize extremely differently than itoa.

  1. Once to copy from itoa::Buffer into arrayvec::ArrayString
  2. Once to return by value from ArrayString::new
  3. Once to pass by value to Result::unwrap
  4. Once to return by value from Result::unwrap
  5. Once to return by value from fmt_int_to_buf
  6. Once to return by value from to_arraystring

See dtolnay/itoa-benchmark#6. You can reproduce the comparison by running cargo run --release to-arraystring:u64 itoa:u64.

It would be helpful to analyze which subset of this chain of copies accounts for the performance difference and whether this can somehow be mitigated without reverting to a worse public API.

performance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions