Object Reuse
As
we saw in the last section, objects are expensive to create. Where it
is reasonable to reuse the same object, you should do so. You need to
be aware of when not to call new. One fairly
obvious situation is when you have already used an object and can
discard it before you are about to create another object of the same
class. You should look at the object and consider whether it is
possible to reset the fields and then reuse the object, rather than
throw it away and create another. This can be particularly important
for objects that are constantly used and discarded: for example, in
graphics processing, objects such as
Rectangle
s, Points,
Colors, and Fonts are used and
discarded all the time. Recycling these types of objects can
certainly improve performance.
Recycling can also apply to the internal elements of structures. For example, a linked list has nodes added to it as it grows, and as it shrinks, the nodes are discarded. Holding on to the discarded nodes is an obvious way to recycle these objects and reduce the cost of object creation.
Pool Management
Most container objects (e.g.,
Vectors, Hashtables) can be reused rather than created and thrown away. Of course, while you are not using the retained objects, you are holding on to more memory than if you simply discarded those objects, and this reduces the memory available to create other objects. You need to balance the need to have some free memory available against the need to improve performance by ...
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