A lightweight alternative to stringstream

I’ve recently been tasked with writing a web application and http server for an embedded (ARM) environment.  My main constraint was keeping the code space small.

Problem

As you may already know, using C++’s stringstream can save a lot of time and effort when parsing and building strings. However, it had one significant caveat for my project:

stringstream has a big code footprint

In my early tests it had an overhead of almost 200 KiB, and that was while using -Os. All that code, just to append a few integers and variables, was not worth the effort. I needed a lightweight and equally convenient alternative…

It then dawned upon me that I might be able to add custom operators to the std::string class myself!

Solution

In order to achieve this I needed to write some global stream insertion operators (I only needed to insert my variables into the string). Here is an example operator for inserting an integer:

In this instance I used the new C++11 std::to_string, but in the project I used our own lightweight itoa.

You can add operators for any type to make conversion and string building a breeze. With these operators I was able to write maintainable, small footprint code to build the web application strings.

Conclusion

Now, I could have just converted every variable into a string manually and appended it to the string, but the stream insertion operator proved to be more readable and maintainable.

I’ve also read that stringstream has questionable performance on a side note.

Please leave a comment if this was interesting or helpful!

 

Leave a Comment