Search code examples
c++memorystlstringstreamostringstream

Is there a way to reduce ostringstream malloc/free's?


I am writing an embedded app. In some places, I use std::ostringstream a lot, since it is very convenient for my purposes. However, I just discovered that the performance hit is extreme since adding data to the stream results in a lot of calls to malloc and free. Is there any way to avoid it?

My first thought was making the ostringstream static and resetting it using ostringstream::set(""). However, this can't be done as I need the functions to be reentrant.


Solution

  • Well, Booger's solution would be to switch to sprintf(). It's unsafe, and error-prone, but it is often faster.

    Not always though. We can't use it (or ostringstream) on my real-time job after initialization because both perform memory allocations and deallocations.

    Our way around the problem is to jump through a lot of hoops to make sure that we perform all string conversions at startup (when we don't have to be real-time yet). I do think there was one situation where we wrote our own converter into a fixed-sized stack-allocated array. We have some constraints on size we can count on for the specific conversions in question.

    For a more general solution, you may consider writing your own version of ostringstream that uses a fixed-sized buffer (with error-checking on the bounds being stayed within, of course). It would be a bit of work, but if you have a lot of those stream operations it might be worth it.