C ++ expressions - which of the two is faster?
I've tried C ++ and I'm especially interested in the performance of the two scripts. A small introduction:
I have a class called Point for experimenting with points given in polar coordinates. The class contains two private double variables, the regular get, set and public function rotate, which take a double argument and add it to our current corner in polar form to create a new Point object.
The following are two different scenarios for rotating a function:
void Point::rotate(double theta) {
double A = getA();
A += theta;
setA(A);
}
void Point::rotate(double theta) {
setA(getA() + theta);
}
My question is simple:
Which one is faster and why?
My understanding is that the first method is to use getA () and then store it in variable A, so it most likely takes longer / less efficient. More generally, when evaluating an expression, do you ever need to store large portions of the expression in other variables and then use them? (With the exaggerated assumption that the "person" who wrote the code will not make a mistake, and anyone who might have to read the code later will understand this perfectly.)
A simple example to clarify my questions:
Let's say we wanted to calculate a + b + c. Is it better to store a + b in a new variable say d and then add d to c? How about calling a function with an argument of another function evaluation?
Thanks in advance!
source to share
Both of these expressions are identical. Ideally, you can always run a test in which you call the expression multiple times in a loop and see the time difference.
However, another way to look at this is to answer the second part of the question, which talks about a+b+c
. When the code is translated into an assembly, a+b
it will be stored in some register anyway and then added to c
, since there is no operation in the assembly to add three digits. Thus, there will be no difference in:
c = a + b + c
and
d = a + b
c = c + d
Also, many other optimizations are done by compilers, which makes things like that irrelevant.
source to share