Java Reference
In-Depth Information
The problem with recursion is that it consumes stack space: The return address and local variables are
stored on the program stack when a method is called. Also, the program state changes that correspond
to a method call might take more time than a simple loop.
Thus, for the function defined previously, the following iterative function may be more efficient:
public static void fact (int n) {
int result = 1;
while (n > 1) result *= n--;
return result;
}
Obviously, the tradeoff is that the iterative constructs are often less readable than the recursive versions.
Using Arrays Instead of Vectors
Vector s are powerful and flexible containers for all kinds of objects. Their main advantage over
arrays is that their size grows dynamically as needed. The disadvantages are
• Many type casts may be needed because a Vector can hold any kind of objects.
Vector s carry some overhead compared to a corresponding array. Actually, Vector s use
an array internally to store their data. Thus, using a Vector requires an additional indirection
step and an additional object when compared to using an array.
• The Vector access methods are synchronized, which also results in some performance
tradeoff. The fact that the size of an array cannot change may help to achieve thread safety
without synchronization.
For these reasons, in some cases it may make sense to use arrays instead of Vector s, especially if the
size of the structure does not change frequently. However, using an array instead of a Vector is not
free of costs. You can't change the size of an array. If an array must be extended, you have to allocate a
new array and copy its entire contents. Thus, for structures that frequently change size, sticking to a
Vector may be a better choice. An alternative that is also used internally by the Vector class is to
allow that the array is larger than necessary. The actual size is stored in a separate variable in that case.
Table 8.1 shows some Vector operations and the corresponding counterparts for arrays.
Table 8.1. Vector Operations and the Corresponding Counterparts for Array Access
Vector
Array
(MyObject) v.elementAt
(i);
v[i];
v.addElement (o); v2 = new MyObject[v.length+1];
System.arraycopy (v, 0, v2, 0, v.length);
v2 [v.length] = o;
v = v2;
v.removeElementAt (i); v2 = new MyObject [v.length-1];
System.arraycopy (v, 0, v2, 0, i-1);
System.arraycopy (v, i+1, v2, i, v.length
- i);
v = v2;
v.insertElementAt (o, i); v2 = new MyObject [v.length+1];
System.arraycopy (v, 0, v2, 0, i-1);
System.arraycopy (v, i+1, v2, i+1,
v.length);
 
 
 
Search WWH ::




Custom Search