Calls to a collection’s toArray(E[]) method should specify a target array of zero size. This allows the JVM to optimize the memory allocation and copying as much as possible.
Note: If you don’t need an array of the correct type, then the simple toArray() method without an array is faster, but returns only an array of type Object[] .
class Foo {
List foos = getFoos();
// inefficient, the array needs to be zeroed out by the jvm before it is handed over to the toArray method
Foo[] fooArray = foos.toArray(new Foo[foos.size()]);
// much better; this one allows the jvm to allocate an array of the correct size and effectively skip
// the zeroing, since each array element will be overridden anyways
Foo[] fooArray = foos.toArray(new Foo[0]);
}
|