Might be a silly question or something I might have just messed up in my head but here we go...
I saw a code example of someone using getPos()
in their own class to retrieve the current position of an object instead of for example using myObj.x
and myObj.y
. That made me think about the use of public variables or generally using helper methods for such things.
By running the following code there was almost a 33% increase in efficiency(time) by using x = x * x
instead of x = getX() * getX()
(In the MyClass void update()
method).
#include <iostream>
#include <chrono>
class MyClass {
public:
int getX() {
return x;
}
int x = 10;
void update() {
for (int i = 0; i < 1000000; ++i) {
// x = x * x;
x = getX() * getX();
}
}
};
int main() {
using std::chrono::high_resolution_clock;
using std::chrono::duration;
MyClass test;
for (int i = 0; i < 10; ++i) {
auto t1 = high_resolution_clock::now();
test.update(); /* What if we would perform test.x actions here instead? */
auto t2 = high_resolution_clock::now();
duration<double, std::milli> ms_double = t2 - t1;
std::cout << std::endl;
std::cout << ms_double.count() << "ms\n";
}
return 0;
}
My question: Is MyClass.x = 10
equivalent to x = 10
(in terms of performance, efficiency, memory allocation etc)? If it is and getX()
is a decrease in performance why do use it instead? Is it just a standard? I understand encapsulation but what would the difference be between a constant MyClass.x
and a private MyClass.x
? We can in both scenarios read the values?
EDIT: I compiled my program with g++ main.cpp
(GNU (MinGW)) and no optimizer flags.