Method Parameters
As I said
at the beginning of the last section, method parameters are low-cost,
and you normally don’t need to worry about the cost of adding
extra method parameters. But it is worth being alert to situations in
which there are parameters that could be added but have not. This is
a simple tuning technique that is rarely considered. Typically, the
parameters that could be added are arrays and array lengths. For
example, when parsing a String
object, it is
common not to pass the length of the string to methods, because each
method can get the length using the String.length()
method. But parsing tends to be
intensive and recursive, with lots of method calls. Most of those
methods need to know the length of the string. Although you can
eliminate multiple calls within one method by assigning the length to
a temporary variable, you cannot do that when many methods need that
length. Passing the string length as a parameter is almost certainly
cheaper than repeated calls to String.length( )
.
Similarly, you typically access the elements of the string one at a
time using String.charAt()
. But again, it is better for
performance purposes to copy the String
object
into a char
array, and then pass this array
through your methods (see Chapter 5). To provide a
possible performance boost, try passing extra values and arrays to
isolated groups of methods. As usual, you should do this only when a
bottleneck has been identified, not throughout an implementation.
Finally, you ...
Get Java Performance Tuning now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.