Do Pigs Fly Yet?


Back in 1999, I wrote about a C++ optimization technique called Return Value Optimization. My summary was:
… in some rosy future years away, return value optimization will be in the hands of compiler writers where it should be, and we won’t have to change our code. And pigs could fly.
Recently a co-worker asked me the question, "so, do pigs fly yet?" In other words, suppose you have this fine readable code:
complex<double> Mult(const complex<double>& a, const complex<double>& b)
{
    complex<double> c;
    double r = (a.real() * b.real()) – (a.imag() * b.imag());
    double i = (a.real() * b.imag()) + (a.imag() * b.real());
    c.real(r);
    c.imag(i);
    return (c);
}
The question is, do you get better code generation if you instead replace it with unreadable and hard-to-debug rubbish like:
complex<double> Mult(const complex<double>& a, const complex<double>& b)
{
    return (complex<double>((a.real() * b.real()) – (a.imag() * b.imag()), 
                            (a.real() * b.imag()) + (a.imag() * b.real())));
}
 
It’s a fair question to ask. Compilers have come a long way since 1999.
 
I ran this snippet through Visual Studio 2005, both on Windows and Xbox 360. The resulting machine code for each of the versions above was exactly the same. The compiler automatically generated the return value optimization. Pretty cool. Pigs were taking wing.
 
However, the compiler can’t always do the right thing. For instance, the original article used the following test bed:
template <class T> T Original(const T& tValue)
{
    T tResult;
    tResult = tValue;
    return (tResult);
}

template <class T> T Optimized(const T& tValue)
{
    return (T(tValue));
}

 
When I ran this code through Visual Studio 2005 with type T equal to std::string, Optimized was unfortunately more optimized than Original. Apparently not all pigs can fly. Yet.
  
Advertisements
This entry was posted in C++. Bookmark the permalink.

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