dimanche 31 mai 2015

What's the cost of using private class data pattern?

I used to have this as a TimeUnit declaration in a library:

Solution1:

typedef boost::posix::ptime TimeUnit;

TimeUnit createTimeUnit( int hours, int minutes );
std::string toString( const TimeUnit& timeUnit );

Let's say I'd like to move this to something more object-oriented:

Solution2:

class TimeUnit : public boost::posix::ptime
{
public:
    TimeUnit( int hours, int minutes );

    std::string toString() const;
};

And now, let's say I don't want libraries using this class to directly depend on boost, so I'd like to use the private class data pattern, to remove any boost reference from my header file:

Solution3:

class TimeUnitPrivate;
class TimeUnit
{
public:
    TimeUnit( int hours, int minutes );
    ~TimeUnit();

    std::string toString() const;
public:
    TimeUnitPrivate* m_data;
};

TimeUnitPrivate being roughly the same as Solution2's TimeUnit and the new TimeUnit being simply:

TimeUnit::TimeUnit( int hours, int minutes ) : 
    m_data( hours, minutes )
{}

TimeUnit::~TimeUnit()
{
    delete m_data;
}

std::string TimeUnit::toString()
{
    return m_data->toString();
}

Solution3 is very smart and I'd save compilation time + limit boost dependencies for sure.

But I was wondering what was the cost of each solution in term of:

  • Memory usage. Will the three solutions of TimeUnit objects need the same amount of bytes to be stored in memory? If not, which one is the best (I suppose it's Solution1)
  • Performance: For sure, Solution3's toString() will be slower than Solution2's (as function cannot be inline, there will be an additional function call needed in the end). That's not a big deal. But I'm wondering if object creation/destruction will be slower...how would the three solutions be sorted in term of performance for object creation/destruction?

Aucun commentaire:

Enregistrer un commentaire