I remember a discussion I recently had with a fellow developer about the memory footprint of private vs public properties. I stated that private ones have less of a footprint than public ones. He claimed it makes no difference. By the way, we were talking about C#.
Who is right and why?
Apparently there are differences in languages. I'm curious what they are as well.
In the context of what language?
In most languages, changing a method's accessibility from public
to private
or vice-versa will not at all affect its memory footprint. This is because the actual implementation and the actual invocation of the method does not change, only the way access to it is enforced (either at compile-time, or at run-time, based on the programming language in question.)
What will have an effect on memory footprint are other qualifiers, such as final
in Java, virtual
in C++, static
, etc. These qualifiers may either directly influence memory footprint (the presence or absence of a corresponding entry in the class vtable
), or indirectly influence memory footprint because of certain optimization assumptions that can be made by the compiler or by the runtime (e.g. non-virtual
, static
and/or final
methods can be inlined, thus arguably increasing performance -- and most definitely increasing memory footprint.)
Of greater importance than memory footprint, when discussing how a method should be qualified, is what you can do to both (1) have the compiler (or the runtime, as depending on the language) validate some of your assumptions and intentions, and (2) convey those assumptions and intentions to the programmer who will review, reverse-engineer, alter, re-factor etc. the code after you:
private
: do other classes, or descendants of this class, need direct access to this method? If not, make it private
.protected
: do descendants of this class (or this class itself), but no other classes (except maybe friend
classes), need direct access to this method? If so, make it protected
.static
: does the method require access to member variables or to this
? If not, it should be static
(e.g. a utility method that depends solely on its arguments)const
: does the method alter member variables or call non-const
member methods on this
or member variables? If not, it should be const
(e.g. a getter)virtual
: will the method need to be overridden? If not, it should not be virtual
abstract
(or pure virtual): does the method need to have an implementation in this class, if this class' descendants will override it? If not, make it abstract
(or pure virtual
)There are miscellaneous articles, lectures and posts out there regarding best practices for the above, transcending the boundaries of many a programming language:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With