[ Team LiB ] Previous Section Next Section

6.5 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 been. 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 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 can reduce the number of objects used by an application by passing an object into a method, which then fills in the object's fields. This is almost always more efficient than creating new objects within the method. See Section 4.2.3 for a more detailed explanation of this technique.

    Previous Section Next Section