Reputation: 235
Maybe obvious but I want to know what and why is the best practice when keeping down the consumption of system resources.
When I want to dynamically expand an Array I can use either
System.arraycopy(arraystuff, 0, tempArray, 0, arraystuff.length);
or
ArrayList
Easiest is of course ArrayList
but is there any reason to use arraycopy
?
Upvotes: 2
Views: 304
Reputation: 140484
Almost always, you should use the higher-level abstraction. You often don't need to care that ArrayList
resizes itself internally, or even that it stores the data in an array (most of the time, you'll have a List
reference, not an ArrayList
); it "just works".
However, the resizing strategy is fixed with ArrayList
: it always resizes by a multiplicative factor of 1.5 in order to amortize the cost of reallocating the array over many additions. This could lead to wasting a lot of space if, say, you only needed to add 1 more element to a full 1,000,000 element list.
True, you can use trimToSize
to get rid of this wasted space, but only after the fact: you'd then be allocating a 1.5M-element array and a (1M+1)-element array. The 1.5M-element array would only be allocated transiently, and could then be GC'd, but that's still more effort than just allocating the (1M+1)-element array directly.
In that case, you might want to have something that you have more control over how it resizes, and in that situation, using System.arraycopy
might be more appropriate.
But really, until you have profiled your code and found that ArrayList
is using too much space, just stick with that.
Note also that you might find Arrays.copyOf
easier to work with than System.arraycopy
for the purposes of resizing an array, because it takes fewer parameters and is type-safe. (It uses System.arraycopy
internally).
Upvotes: 3
Reputation: 8363
System.arraycopy()
is a native method while ArrayList
is a high-level Java implementation, which will eventually call System.arraycopy()
. Therefore, in terms of performance, System.arraycopy()
is definitely better. But in general, unless every bit of performance matters for your application, it is generally more favorable to use a List
.
Upvotes: 1