Reputation: 2127
I saw that in some programs it is recommended the use of public
variables instead of get
and set
functions for a better performance. I know that this is considered a bad practice. I also know that the compiler could make the get
and set
inline
. Doesn't this mean that they behave like a variable with no performance fall-outs?
Upvotes: 1
Views: 2999
Reputation: 1407
The compiler will most probably inline these functions (see how), and there will be no function call overhead. I would avoid the getter, setter, and public member variables and instead think why these are used and provide a function to do that in that class. Most of the getter, setter, and public member variables can be removed this way.
Upvotes: 5
Reputation: 29976
They should be the same performance-wise, if the compiler really choses to make them inline. The inline
keyword is just a hint for the compiler, it must not strictly obey it, and vice-versa: it can make a function that is not marked with inline
keyword, an inline one.
However, if for some reason the compiler will not make them inline, you will obviously lose some performance on the calls.
Upvotes: 1
Reputation: 53067
You can always expect compilers to inline trivial getters and setters and so you'll get identical performance.
There can be differences though, such as not being able to get a pointer or reference to the private member when using getters/setters if you're returning by value. Also, setters may have an extra copy or move operation.
Anyway, if you want public access then just use public variables. They are best practices.
Upvotes: 1