1. Exceptions are not necessarily expensive to process, though they should be used
only when appropriate.
2. The deeper the stack, the more expensive to process exceptions.
3. The JVM will optimize away the stack penalty for frequently created system ex-
4. Disabling stack traces in exceptions can sometimes help performance, though cru-
cial information is often lost in the process.
Strings are central enough to Java that their performance has already been discussed in sever-
al other chapters. To highlight those cases:
It is common to create many string objects that contain the same sequence of characters.
These objects unnecessarily take space in the heap; since strings are immutable, it is of-
ten better to reuse the existing strings. See Chapter 7 for more details.
While Java strings are UTF-16 encoded, most of the rest of the world uses a different en-
coding, so encoding of strings into different charsets is a common operation. The en-
code() and decode() methods of the Charset class are quite slow if they process only
one or a few characters at a time; make sure that they are set up to process full buffers of
data, as discussed earlier in this chapter.
Java EE application servers often have special handling for encoding static strings (from
JSP files and so on); see Chapter 10 for more details.
String concatenation is another area where there are potential performance pitfalls. Consider
a simple string concatenation like this: