Avoiding Garbage Collection
The canonicalization techniques I’ve discussed are one way to avoid garbage collection: fewer objects means less to garbage-collect. Similarly, the pooling technique in that section also tends to reduce garbage-collection requirements, partly because you are creating fewer objects by reusing them, and partly because you deallocate memory less often by holding on to the objects you have allocated. Of course, this also means that your memory requirements are higher, but you can’t have it both ways.
Another technique for reducing garbage-collection impact is to avoid
using objects where they are not needed. For example, there is no
need to create an extra unnecessary
Integer
to parse a
String
containing
an int value, as in:
String string = "55"; int theInt = new Integer(string).intValue( )
Instead, there is a static method available for parsing:
int theInt = Integer.parseInt(string);
Unfortunately, some classes do not provide static methods that avoid
the spurious intermediate creation of objects. Until JDK Version 1.2,
there were no static methods that allowed you to parse strings
containing floating-point numbers to get doubles
or floats. Instead, you needed to create an
intermediate Double object and extract the value.
(Even after JDK 1.2, an intermediate
FloatingDecimal
is created, but this is arguably due to good abstraction in the programming design.) When a class does not provide a static method, you can sometimes use a dummy instance to repeatedly ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access