Alex Apas
Alex Apas

Reputation: 65

C++ expressions - which one of the two is faster?

I have been trying out C++ and I am particularly interested in the performance of two scripts. A small intro:

I have a class called Point for experimenting with points given in polar coordinates. The class contains two private double variables, the usual functions get, set and the public function rotate which takes a double argument and adds it to our current angle in the polar form to produce a new Point object.

Below follow two different scripts for the function rotate:

void Point::rotate(double theta) {
    double A = getA();
    A += theta;
    setA(A);
}

void Point::rotate(double theta) {
    setA(getA() + theta);
} 

My question is straightforward:

Which one is practically faster and why ?

I understand that the first method has to use getA() and then save that into the variable A so most likely, it takes longer/is less efficient. In more generality, upon calculating an expression, is there ever a need to save big parts of the expression in other variables and then use these ? (With the exaggerated assumption that the "person" who wrote the code will not make a mistake and everyone who might have to read the code later will perfectly understand it.)

A simple example to clarify my questions:

Say we wanted to calculate a+b+c. Is it better to save a+b in a new variable, say d, and then add d to c ? How about calling a function with argument another function evaluation ?

Thanks in advance!

Upvotes: 3

Views: 245

Answers (1)

therainmaker
therainmaker

Reputation: 4343

Both of these expressions are identical. Ideally you could always run a benchmark in which you call the expression multiple times in a loop and see the time difference.

However, another way of looking at it is by answering the second part of question, which speaks about a+b+c. When the code will be translated to assembly, a+b will anyway be stored in some register and then added to c, as no operation for 3 figure addition is present in assembly. So, there won't be a difference in:

c =  a + b + c

and

d = a + b
c = c + d

Also, many other optimisations are done by compilers, which result in such things not making a difference.

Upvotes: 7

Related Questions