Java Reference
In-Depth Information
it takes to reallocate and copy each individual string. In Java, this antipattern
frequently occurs within loops that build queries, process parameters, or build
XML documents. Instead, you should use a single StringBuffer and append
each successive string into the buffer. Alternatively, you can keep the string
String x = "Hello " +
name +
", your birthday is " +
In this way, you let the optimizer do the work for you. It will allocate a single
string buffer to process the entire string, saving memory and plenty of CPU
We have seen that collections can have a dramatic impact on memory, because
they tend to be used to manage objects in large numbers. Collections can
affect memory in other ways as well. For example, large multidimensional
arrays can consume staggering resources. Collection choice can also affect
memory and performance.
Collections and allocation
Different Java types handle memory resources differently. Arrays allocate
memory when they're created. Other collection types, such as sets, vectors,
hash tables, and lists, allocate memory when items are added. Many times,
preallocation is a good thing. If you know that you'll be allocating an explicit
number of objects, that you'll be accessing the collection randomly or exclu-
sively by a numerical index, and you know precisely when the resource will be
used, then an array could be a good choice. Other times, preallocation can
cause you to make incorrect assumptions or allocate much more memory than
you are likely to use. Beginners frequently prefer arrays to more robust collec-
tions. If you know that you'll be adding a variable number of objects through-
out the life cycle of the collection, or that access will be random by some other
key, then a hash table may be a better choice.
Collections and access patterns
The type of access will also have an impact on the collection choice. If you
must frequently access by a key other than an index, then a hash table, dictio-
nary, or b-tree may be a better data structure than an array. If the order does
not matter, a set may be a better choice. The key for success is to pick an
Search WWH ::

Custom Search