Java Reference
In-Depth Information
Mini-Antipatterns: Little Hogs
One little hog cannot eat much, but many little ones can have devastating
appetites. This chapter title may have led you to expect a whole chapter on
dealing with strings and the little things that a programmer can do to save a
few bytes here and there. This section is the last in the chapter because I do
not think that little optimizations should be emphasized, especially in cases
where they can affect performance. There are some places where memory can
become an issue, such as in pervasive environments, very large object trees,
and massive collections of objects. In these extreme cases, it makes sense to
consider the microtechniques, which can collectively yield considerable sav-
ings. In other cases, I do not advocate reckless or careless memory use. I sim-
ply prefer readability to a few bytes of memory savings, and trust that I can
make up the difference by optimizing the most important test cases first. With
that in mind, let's consider some of the little memory hogs that can add up. In
most cases, performance problems will be found in higher level designs, so
low-level optimizations should be saved for later.
String manipulation
In memory-constrained situations, you should pay close attention to the pro-
liferation of strings. A common offender is the + operator. If we string several
+ operators together to build a string, then each string argument will allocate
an additional object and force more than one copy operation. This can get
expensive, in terms of memory and performance. To clarify, consider the two
following string treatments:
String s = "this code uses plus to break between "+
"lines but doesn't result in any extra "+
"objects as it still counts as a compile-time"+
This string works. The optimizer will allocate one StringBuffer , build the
string up there, and then turn it into a single string. The following is much
more dangerous:
String x = "Hello ";
x += name;
x += ", your birthday is ";
x += birthday;
This fragment will take significantly longer to execute, because in this case,
each individual string will be allocated and copied. It does have a memory
impact, although it is negligible. The bigger impact is the cumulative time that
Search WWH ::

Custom Search