Reputation: 11
If I have a class File
class File {
public:
File(int length);
getLength(); //returns length int value
int length;
}
Between File.value
(implying it's not private/anything else, so it can be accessed directly) and File.getValue()
, what is the option which impacts performance less?
Upvotes: 0
Views: 103
Reputation: 1811
Without optimization the getter will cost more. A value can be accessed with a single 'mov' instruction, but a function call (for the getter) will need many more instructions (at least an additional 'call' and 'ret').
If you define your getter as 'inline' then most of the compilers will remove the function call and the performance will be the same as accessing the member variable directly. 'inline' methods and functions will most likely be implemented within the header file (because every translation unit needs access to the function source).
Most modern compiler will even inline getters which are not marked as 'inline' if optimizations are enabled. Some compilers will online remove the function call for calls from within the same module (.cpp file). At least Visual C++ removes the function call even if it is called from another module or even project if 'link time code generation' (LTCG) is active for both parts.
Note: Even if a modern compiler does not use the 'inline' keyword to decide if a method should be inlined, it still avoids the 'multiple definitions' linker error you normally get if you implement a method within a header file which is used from multiple modules.
There is a huge chance that, if public access to the member variable is ok for you, you do not need a getter (and/or a setter) at all.
Upvotes: 3