Given a singleton class (only one instance ever) is it more efficient to access a variable directly rather than using setter/getters? Or is the difference sufficiently insignificant that getters/setters are still better programming practice? TIA.
It is a good practice to prevent users from fiddling with variables directly and introduce methods (i.e. getters/setters) to access them.
In your given example or more precisely in your application it may make no difference, however, if you were to use such singleton object in concurrent environment, you wouldn't have the way to synchronise reading/writing.
This isn't really something you should be even considering. First of all, it's almost impossible to make the choice without prematurely optimizing the code - optimizing based on what you think will be efficient, instead of what is measurably efficient. Because it's such a low-level function, if you chose wrong, the cost of re-coding is likely to be prohibitive,
Fortunately, neither case would make much performance difference, The real performance boosts don't come from low-level twiddling, they come from good algorithms. The most highly-optimized bubble search in the world gets left in the dust by a heapsort when the conditions are right (and vice versa!).
Also, the Java compiler and runtime are heavily optimizing. Just because you coded a method call doesn't mean that Java cannot recognize the simplicity of the operation and internally translate it to a direct fetch/store.
I recommend accessor methods, though. They're easier to temporarily attach debugging and profiling extensions to.
When it comes to destroying a civilization, gas chambers cannot hold a candle to echo chambers.
posted 3 weeks ago
That is the information I was looking for. Although a bit counter intuitive, I guess that is why using setters/getters is considered good programming practice. Thanks.
Don't mess with me you fool! I'm cooking with gas! Here, read this tiny ad: