Memory optimization of public methods in java
https://softwareengineering.stackexchange.com/questions/393181
-
26-02-2021 - |
質問
Does it optimize a program in java to declare methods private wherever they can be private or it doesn't change a thing and it's just a question of encapsulation? I was asking myself if declaring a method public was heavier than a declaring it private in terms of memory consumption.
解決
private
methods can never be overridden, whereas protected
and public
methods can be overridden.
As a consequence of this, the underlying runtime knows that for private
methods:
- There is no need to place them in the method table
- It can invoke them using non-virtual dispatching
By contrast, protected
and public
methods are most likely placed into the method table, and, analysis would take place to determine whether to invoke using virtual dispatch through the method table or not. (To err on the side of correctness, virtual dispatch would be used. Due to dynamic class loading the method may potentially be overridden sometime in the future, which might require adjustment to optimistic choices.)
The above does not take into account final
classes: methods in final classes share the above discussed qualities among all methods private
, protected
, and public
.
But worrying about this is micro optimization. It is very unlikely that virtual dispatch will have a meaningful effect on the performance or memory consumption of your application.
他のヒント
Access modifiers like private
and public
have no effect on the resource requirements of a Java program. They exist largely as documentation and aids to understanding for human readers and writers of the code. Even when information about the status of a field or method is retained at runtime, it's likely to be stored in a bitfield-like structure, so either value takes the same amount of memory.
In short, making things private
does not optimize computer memory (RAM) in any way. It can, however, be better for human memory, because an API with fewer visible members is easier to understand and easier to remember than an API with everything public
.