[eigen] prefix vs. postfix increment

[ Thread Index | Date Index | More lists.tuxfamily.org/eigen Archives ]

This might sound nitpicky, but I think it should be mentioned since performance seems to be one of the main goals of Eigen (and it's something everyone should do anyways).  I've noticed when looking through the source code, that postfix increment is being used in places where prefix increment would suffice.  Some compilers will automatically fix this for you when possible, but many times they can't due to the possibility of overloaded operators with user-defined types.  Also, some compilers just don't do it even with basic types, depending on optimization settings.  What I'm talking about is this:

for(int j = 0; j < cols(); j++)
      for(int i = 0; i < rows(); i++)

should be:

for(int j = 0; j < cols(); ++j)
      for(int i = 0; i < rows(); ++i)

The reason is that postfix increment needs to return the original value, which requires it to cache that value in a temporary variable, incurring a copy (which is even more expensive with a complex type like an STL iterator).  To make the performance difference more clear, think about how you would overload both operators for some class "Integer":

// Prefix operator
Integer Integer::operator++()
    return ( *this + 1 );

// Postfix operator
// Note that C++ discerns between the prefix and postfix
// overloads by requiring the postfix overload to have an
// unused "dummy" integer parameter...a kludge if I ever saw one.
Integer Integer::operator++( int dummy )
    Integer previousValue = *this;

    *this = *this + 1;

    return previousValue;


Mail converted by MHonArc 2.6.19+ http://listengine.tuxfamily.org/