Java Reference
In-Depth Information
keep in mind that, even though devices are not as resource-constrained as
they used to be in the past, MIDlets must be developed with consideration
for utilization of system resources. This ensures that they perform well and
remain responsive, not only in easy scenarios but also when conditions
become harsh, with many applications installed and running, fighting for
processor time and memory resources.
9.2.2 Handle Strings Efficiently
Java strings offer great convenience in handling text, although it has
frequently been argued that the String API encourages inefficient code.
Clearly, it is our job to use strings efficiently and Java, including Java ME,
comes with some built-in mechanisms that can help.
Use StringBuffer
StringBuffer is the ideal tool for any string composition that involves
concatenating several strings. For example, the following code that con-
catenates five strings could be rewritten with StringBuffer and offer
much better performance.
String message = "Error: " + emsg + " [code=" + code + "]";
The code above results in the creation of several intermediate strings
holding intermediate concatenation results. The intermediate strings are
discarded immediately. So, not only have we taken time creating several
unnecessary strings, the garbage collector also has considerably more
work to do to clean up the discarded objects. The right way to do this is
as follows:
StringBuffer messageBuf = new StringBuffer();
messageBuf.append("Error: ");
messageBuf.append(" [code=");
String message = messageBuf.toString();
Granted, this looks less concise, but it can profoundly improve appli-
cation performance.
Working with String and StringBuffer can result in large
amounts of memory being used unexpectedly. The problem is this:
when StringBuffer.toString() creates a String , the newly cre-
ated String uses the StringBuffer character array. This means that if
a StringBuffer with a 1 KB capacity only holds a 10-character string,
the new String also uses a 1 KB character array to store 10 characters.
Search WWH ::

Custom Search