Home > Frameworks > boost::compressed_pair


The boost::compressed_pair is very close to the common std::pair except that it will optimize its memory size if one or two of its templated classes have a size of zero.

As a reminder, when an empty class is allocated, C++ will still allocate a small block of memory, so that the object can point somewhere in memory.  This requirement leads to wasted memory, and compressed_pair is meant to prevent such waste.

Otherwise, boost::compressed_pair act just as a normal std::pair.

To test its behavior, I defined two classes:

class Empty {};  // technically a zero sized class
class DoubleInt {int var[2];};  // size of 8 bytes

Then I simply printed the sizeof of different pairs permutations, from both std::pair and boost::compressed_pair like so:

cout << "std::pair<Empty, Empty>: "
    << sizeof(std::pair<Empty, Empty>) <<endl;
cout << "std::pair<DoubleInt, DoubleInt>: "
    << sizeof(std::pair<DoubleInt, DoubleInt>) <<endl;
cout << "std::pair<Empty, DoubleInt>: "
    << sizeof(std::pair<Empty, DoubleInt>) <<endl;

cout << endl;

cout << "boost::compressed_pair<Empty, Empty>: "
    << sizeof(boost::compressed_pair<Empty, Empty>) <<endl;
cout << "boost::compressed_pair<DoubleInt, DoubleInt>: "
    << sizeof(boost::compressed_pair<DoubleInt, DoubleInt>) <<endl;
cout << "boost::compressed_pair<Empty, DoubleInt>: "
    << sizeof(boost::compressed_pair<Empty, DoubleInt>) <<endl;

And here’s the result, where the compressed_pair optimization is pretty obvious:

std::pair<Empty, Empty>: 2
std::pair<DoubleInt, DoubleInt>: 16
std::pair<Empty, DoubleInt>: 12

boost::compressed_pair<Empty, Empty>: 1
boost::compressed_pair<DoubleInt, DoubleInt>: 16
boost::compressed_pair<Empty, DoubleInt>: 8

Now I wonder, for simple precautions, if I should start using compressed_pair all the time.  Empty classes are not very commons tho, especially the need to use them in a pair…

Categories: Frameworks
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: