I'm seeing plenty of code has been refactored in recent years to use a
" public static final X INSTANCE" field rather than a normal
Often this is a good thing since memory allocation rate is *typically*
our limiting factor to improve performance, yet let's be mindful that
this pattern has some drawbacks as well.
An example is bootstrap code: if ComplexStuff.INSTANCE is used only a
very limited amount of times, and during bootstrap, having it in a
static final field will ensure that the memory of this instance is not
going to be freed up after it is no longer needed.
A similar pattern is to declare a Logger in a class as a "static
final" yet only ever use it in a catch block which is only going to be
executed to log a critical bootstrap error.
The Logger instance is taking quite some memory as well, so it would
be best to just create the Logger on the fly within the catch block,
essentially betting that this is either never going to be used (or
when it's used we want to crash fast anyway).
On top of memory usage, there's also the actual time it takes to
initialize such things; if it's rarely used, let's not use the static
final field as it enforces it to be initialized even when unnecessary
(unless being very careful).
Of course in most cases this makes no significant difference, so
should not worry anyone, but in some cases thinking about the
tradeoffs of such patterns can make a very good impact on overall
memory needs; e.g. I just removed a single singleton and this saves me
~20% of the overall memory during a bootstrap efficiency test.
hope you find it interesting!
Show replies by date