Optimization

T

Thorsten Kiefer

Hi,
following issue :

class X {
//very complicated and memory intensive stuff
];

inline X operation(const X &a,const X &b){
X c;
c = ....a....b....; // some operation
return c;
}

main(){
X s,t,v;
v = operation(s,t);
}


My question:
The function "operation" creates an instance of X, operates on it, copies it
into the return buffer and destroys it. Then the return buffer is copied
into v.
Can the optimizer optimize this such that "operation" operates directly on v
instead of an intermediate instance of X ?
I guess this would be a huge performance increase, wouldn't it ?


Regards
Thorsten
 
R

Roland Pibinger

inline X operation(const X &a,const X &b){

My question:
The function "operation" creates an instance of X, operates on it, copies it
into the return buffer and destroys it. Then the return buffer is copied
into v.
Can the optimizer optimize this such that "operation" operates directly on v
instead of an intermediate instance of X ?

Maybe. Who knows. Check your compiler documentation. You probably need
to set a certain compiler flag.
I guess this would be a huge performance increase, wouldn't it ?

You can do that without vague reliance on compiler oprimizations:

inline X& operation(const X &a,const X &b, X &out) {
// ....
return out;
}

Best regards,
Roland Pibinger
 
M

Markus Schoder

Thorsten said:
Hi,
following issue :

class X {
//very complicated and memory intensive stuff
];

inline X operation(const X &a,const X &b){
X c;
c = ....a....b....; // some operation
return c;
}

main(){
X s,t,v;
v = operation(s,t);
}


My question:
The function "operation" creates an instance of X, operates on it, copies
it into the return buffer and destroys it. Then the return buffer is
copied into v.
Can the optimizer optimize this such that "operation" operates directly on
v instead of an intermediate instance of X ?

The way you have written the code it will be difficult for the compiler to
optimize since you assign an object and operation() constructs a new object
these are very different things so the compiler will likely not be able to
elide one or the other.

If you write instead:

int main(){
X s,t;
X v = operation(s,t);
}

chances are that v will be constructed in the operation() call directly this
is called return value optimization (RVO).
 
T

Thorsten Kiefer

Thanks, that's a good tip !
Maybe i should check the Assembler code that the compiler generates.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,802
Messages
2,569,662
Members
45,431
Latest member
AidaVardon

Latest Threads

Top