Java Reference
In-Depth Information
If the
StringBuffer
is modified, the
StringBuffer
array is copied
in its entirety and then modified. Now both the
String
and
String-
Buffer
have separate 1 KB character arrays. We have just lost the best
part of 1 KB of memory! Repeating the process continues to use excessive
memory, as we generate 10-character strings each of which uses a 1 KB
character buffer.
Use
InputStreamReader
toReadStrings
This is a pretty obvious statement, but unfortunately it appears to be
necessary to mention because we often see developers casting
byte
to
char
. The problem with casting here is that we are ignoring the encoding
that was used to store characters in the first place. Unicode formats,
especially UTF-8 which is commonly used in Java programs, can have
a variable number of bytes per character hence they cannot be decoded
byte-by-byte.
InputStreamReader
efficiently performs the conversion
for us so that we don't need to worry about decoding.
Use
String.intern()
(ornot)
In essence,
String.intern()
takes a string and returns a JVM-wide
unique reference to a string with the same content. This helps preserve
memory because it allows us to have only one
String
instance repre-
senting a specific string. For example, all string constants in our classes
are interned.
Although
String.intern()
is available for use in any Java appli-
cation, we should only use it with great care. There is no mechanism
to un-intern a string, so once you have called
String.intern()
,it
remains in memory until JVM shutdown. It has been suggested that if
we use
String.intern()
, we can use reference comparison instead
of the normal
String.equals()
for comparing strings. For example,
consider the following code:
// Be careful about using intern - it has hidden costs
string1 = string1.intern();
...
string2 = string2.intern();
...
if(string1 == string2)
{
/* do something */
}
A call to
String.intern()
includes a call to
String.equals()
so using
String.intern()
to 'speed up equals' is usually not a great
idea.
A good use of
String.intern()
may be if we have many occur-
rences of a particular string throughout the application runtime. Using
String.intern()
, we can preserve memory that would normally be