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!