C++ Code

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.


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!


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.


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!


By Pieter Jordaan

Pieter is a Ph.D student in computer and electronic engineering at the University of the North West. His field of study is a hybrid approach to relational and non-relational databases.

He also enjoys playing the guitar and singing songs. He is married to the beautiful co-author Jeanne-mari Jordaan

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.