Reputation: 821
Which of these is more efficient? :
ArrayList<Integer> list = new ArrayList<Integer>();
for(int a : list){
log.i(tag, a + "");
}
SparseIntArray list2 = new SparseIntArray();
int count = list2.size();
for(int j = 0; j < count; j++) {
log.i(tag, list2.get(j) + "");
}
Or, is there a faster way to read the contents of the list?
Upvotes: 1
Views: 1961
Reputation: 22105
For-each loops like your first example are almost always preferable when you don't need an index variable for other reasons.
Edit: ArrayLists would iterate more efficiently (in your example, repeatedly calling "get") than SparseIntArray because lookups are constant time as opposed to logarithmic time. This will depend a bit on your use case though--if your keys are sparse then SparseIntArray will save you a lot of memory space.
I would point out that the SparseIntArray can have gaps in the indicies, meaning that looping over every value between 0 and Size is not only inefficient, but it will also return 0 for every missing index, which is probably not your intended behavior.
Upvotes: 2
Reputation: 4908
SparseIntArrays map integers to integers. Unlike a normal array of integers, there can be gaps in the indices. It is intended to be more efficient than using a HashMap to map Integers to Integers.
Upvotes: 2
Reputation: 183602
Efficiency, in this case, is irrelevant, since those two do completely different things.
I think you realize that your ArrayList
example iterates through all the elements of the array-list.
What you don't realize is that your SparseIntArray
example does not iterate through all the elements of the sparse-integer-array, because the keys of a sparse-integer-array do not range from zero to array-size-minus-one. Rather, its keys are arbitrary integers. A sparse-integer-array has as much in common, interface-wise, with HashMap<Integer, Integer>
as with ArrayList<Integer>
.
(This, by the way, relates to a general rule of software design: it is better for your code to be correct than efficient. You can always take correct, clean code and find ways to improve its performance; but it's very hard to take fast, buggy code and find ways to make it correct.)
Upvotes: 15