Add vs Add
Yesterday, Google release update for [appcompat v22.1][1] one of interesting thing is Sorted List one thing that comes to my mind is what method add in SortedList actually look like. Because i’m curious about how SortedList sort their data.
And then i want to measure about the performance of ArrayList and SortedList. I create a code to measure the ArrayList Peformance :
long start = System.nanoTime();
int [] sample = new int[size];
for (int i = 0; i <= 100000; i++) {
if (i == size ){
size = size + (size >> 1);
sample = Arrays.copyOf(sample, size);
}
sample[i]= i;
}
long last = System.nanoTime();
System.out.println("finish in : " + (last - start));
This is actual code for add in ArrayList :
public boolean add(E object) {
Object[] a = array;
int s = size;
if (s == a.length) {
Object[] newArray = new Object[s +
(s < (MIN_CAPACITY_INCREMENT / 2) ?
MIN_CAPACITY_INCREMENT : s >> 1)];
System.arraycopy(a, 0, newArray, 0, s);
array = a = newArray;
}
a[s] = object;
size = s + 1;
modCount++;
return true;
}
This is actual code for growing in SortedList :
private void addToData(int index, T item) {
if (index > mSize) {
throw new IndexOutOfBoundsException(
"cannot add item to " + index + " because size is " + mSize);
}
if (mSize == mData.length) {
// we are at the limit enlarge
T[] newData = (T[]) Array.newInstance(mTClass, mData.length + CAPACITY_GROWTH);
System.arraycopy(mData, 0, newData, 0, index);
newData[index] = item;
System.arraycopy(mData, index, newData, index + 1, mSize - index);
mData = newData;
} else {
// just shift, we fit
System.arraycopy(mData, index, mData, index + 1, mSize - index);
mData[index] = item;
}
mSize++;
}
And This is average result of time when i want to add item to list (Using Linux Mint 15, 8Gb Ram, Core I5 1,7 Ghz)
ArrayList : 5652403
SortedList : 605537209
Yes, time to add and growing item in sorted list is taking more time. Its because they grow the array by +10 different from arraylist that growing item is by >>1 or by 2 times.
Conclusion : Do not use SortedList because the actual purpose to use in recyclerview not to process data.