fmt::Display takes 20% of cpu time but I don't even use it in my code

Hi,

I have code that does a lot of bitwise oprations.

I ran cargo flamegraph and noticed that core::fmt::num::imp::_<impl core::fmt::Display for i32>::fmt take about 20% of the time though I don't even use i32 in my code.

Is there a way to improve performance?

The flamegraph should show you what intermediate functions are formatting i32s (although it can be non-obvious in the code, hidden behind println! and format! macros). You aren't printing any numbers at all?

3 Likes

In addition to macros like write! and println!, calling to_string also uses the Display trait.

Once you find where the i32-to-string conversions are happening in your code, either eliminate them or consider using the itoa crate.

6 Likes

Oh... that make sense.
It is my test where I loop through integers and then call to_string on them.
Thank you

1 Like

What?? Are int conversions to_string() slow by default?

Because to_string is generic, it goes through a few layers of formatting code, which might not all get optimized away. And it allocates a new String for each conversion, which also adds overhead.

Even optimized string conversions are surprisingly slow, and to_string needs to allocate, which does have cost. (Things like write!(f, "foo: {}", bar.to_string()), in particular, are a bad idea because of the intermediate steps.)

Good to know... So this itoa crate could be useful when having do display numbers in a game.
I already have so many dependencies. Anyway: this one was solved. I will complain somewhere else if needed :slight_smile:

If you were having performance issues with displaying numbers, one thing you might do is write a std::fmt::Write implementation such that you can write the characters making up formatted values directly into your text-renderer, without going through String allocation.

Not saying you should necessarily do that, just that it's an option, and using the built-in formatter does not necessarily imply allocating.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.