Compiler Optimizations

Posted by Matt | Filed under ,

I am in the process of profiling our application, and I wanted to do some tests to prove/disprove my hypothesis.

I hypothesize that:

class A { ... };

A Foo()
{
    A result;
    // ...
    return result;
}

void main()
{
    A a = Foo();
}

is slower than:

class A { ... };

void Foo(A &a)
{
    // Do stuff to a
}

void main()
{
    A a;
    Foo(a);
}

I thought the first example above would have 2 constructor calls, followed by 2 operator = calls.  I thought that passing in the result variable to be modified would be less expensive with only a single constructor call with no copy calls.

Running each of the examples in the debugger, I observed one constructor call followed by one copy constructor call for the first example, and one constructor call for the second example.

This was the case when running using a debug configuration.

However, running with a release configuration, I ended up with one constructor call in total for the first example.  It appears that the compiler arranged memory such that the "temporary" result in the function Foo() was actually initializing and modifying the local variable in main().  This is actually quite efficient.  No copying of data was occurring while moving from scope to scope.

Another observance was that:

A a = Foo();

is not equivalent to:

A a;
a = Foo();

The first one really is a copy constructor call (when in debug).  The second example is an operator = call.

What did I learn from all this? 

The work I was doing to attempt to reduce data copying was almost in vain (in my case) since the compiler was doing some very good optimizations.

This may not be the case for your data, so it's best to do your own benchmarks to see if the compiler is helping you or not.

In the end, I still believe that passing the result variable is better than returning the result variable when working blind, but the compiler makes them pretty much equivalent in some cases.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading