For example, the object is frequently called, but it is instantiated right before each time it is called and garbage collected after finish using it, and repeat this process again next time, the processing time of the processing thread will definitely be increased as there is cost of time on doing instantiation for objects and garbage collection.
However, how about if the object's instantiation and GC could be reduced (i.e. declaring the variable as "static", "final", "static final")? It should certainly reduce the time of execution time as the instantiation is refactored to right after the class is loaded by JVM, but before the function is called. The number of GC would significantly reduced for the relevant objects.
If you agree to the above, then the next step we need to think, is how to justify when a variable should be declared as "static", "final", "static final". It is important as declaring the above modifiers incorrectly may induce mutability issue, especially in a multi-thread environment.
Below idea may help us to make the correct judgement and declaration:
- Variable's assigned value will not be changed during the class's lifetime? Yes: "final"
- Variable will be called (referenced) frequently during the class's lifetime? Yes: "static"
- Both (1) and (2) also stand? Yes: "static final" or "final static"
Here is a graph which hopes could help on going through the decision making:
P.S. Here is how "frequently called" of a variable is being defined by me base on my experience. Hope it would be helpful too.
"Frequently called" Definition
On defining whether a variable will be called "frequent", 2 modifiers of the variable could be helpful on judgement: "public", "private"."public"
If a class variable is declared as "public", then we should assume it will be called frequently. In order to reduce the initialization time of this variable's instance while being called, we should declare it as "static"."private"
(1) If a class variable is declared as "private", and it will be called (referenced) in a run() method or in a loop (e.g. for-loop, while-loop), then we should assume it will be called frequently and should declare it as "static". In this case, it would be declared along as "final" to guarantee thread-safe in most cases.(2) Even if a variable is declared as "private", but it will be referenced through some static methods in the same class, we should assume the variable will be called frequently and should declared it as "static" (actually you have no other choices as it is limited by Java). [For this case, is the simple class should also declare a private constructor to avoid others instantiating it explicitly and accidentally ]

沒有留言:
張貼留言