Skip to content

Integer to_string is slow #135543

Description

@jh05013

On my machine, the following code runs in 3 seconds in stable version, release build:

// (EDIT: made it compile)
fn main() {
    for i in 0..100000000u32 {
        let s = i.to_string();
        assert!(s.len() > 0);
    }
}

whereas the C++ counterpart runs in 1.2 seconds with -O2:

#include <string>
#include <cassert>
int main() {
    for(unsigned int i=0; i<100000000; i++){
        std::string s = std::to_string(i);
        assert(s.size() > 0);
    }
}

I've found that most of the time loss comes from passing &str through a formatter instead of directly memcpying; replacing to_string with _fmt with .to_owned() at the end speeds it up to around 1.6s.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-fmtArea: `core::fmt`C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing such

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions