Java Reference
In-Depth Information
Eliminating instance fields in an object can help make the object smaller, but there is a gray
area here: what about object fields that hold the result of a calculation based on pieces of
data? This is the classic computer science trade-off of time versus space: is it better to spend
the memory (space) to store the value, or better to spend the time (CPU cycles) to calculate
the value as needed? In Java, though, the trade-off applies to CPU time as well, since the ad-
ditional memory can cause GC to consume more CPU cycles.
The hashcode for a String , for example, is calculated by summing an equation involving
each character of the string; it is somewhat time-consuming to calculate. Hence, the String
class stores that value in an instance variable so that the hashcode need only be calculated
once: in the end, reusing that value will almost always produce better performance than any
memory savings from not storing it. On the other hand, the toString() method of most
classes does not cache the string representation of the object in an instance variable, which
would consume memory both for the instance variable and the string it references. Instead,
the time required to calculate a new string will usually give better performance than the
memory required to keep the string reference around. (It is also the case that the hash value
for a String is used quite frequently, and the toString() representation of an object is of-
ten used quite rarely.)
This case is definitely a your-mileage-may-vary situation, and the point along the time/space
continuum where it makes sense to switch between using the memory to cache a value and
recalculating the value will depend on many factors. If reducing GC is the goal, then the bal-
ance will swing more to recalculating.
1. Reducing object sizes can often improve the efficiency of GC.
2. The size of an object is not always immediately apparent: objects are padded to fit
on 8-byte boundaries, and object reference sizes are different between 32- and
64-bit JVMs.
3. Even null instance variables consume space within object classes.
Search WWH ::

Custom Search