Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java performance and memory: LinkedList & arrays

I'm building an Android app (so machines with limited resources) and I want to know how picky I should be with LinkedLists.

I know that arrays are the lightest containers and are the best at random access, so they're obviously the ideal choice if you only consider performance. However, their rigidness is a pain when you don't know how big your list will be.

So here's my question: is it worth it to systematically use the following type of mechanism in classes who have one or more list of unpredictable size:

public class unpredictable
public Object[]realArray;
private LinkedList<Object> temp;

//what using classes will call to add items
public void add(Object item) 
{
    temp.add( item );
}

//what the outer class calls when it knows there's nothing left to add 
public void doneAdding() 
{
    realArray = new Object[tmp.size()];
    transferAndRecycle();
}

private void transferAndRecycle()
{
    // copy items from linkedlist to array
}

So I guess I'm asking if it's worth it to take the extra steps to get rid of the extra space Java's LinkedList object takes?

Any input? Thanks

like image 806
soBinary Avatar asked Dec 22 '22 11:12

soBinary


2 Answers

I think you are providing a lot of services that the ArrayList class already contains. The ArrayList gives you O(1) element access; with a linked list it's O(n). The underlying mechanism of an ArrayList is an array. You can control the size of this array by manipulating the capacity.

Look closely at ArrayList -- you may avoid reinventing some wheels.

Additional thought: Arrays and Generics don't play nicely. ArrayLists do. That is a small item but could be important to you.

like image 66
ncmathsadist Avatar answered Dec 24 '22 01:12

ncmathsadist


In addition to what ncmathsadist already said:

Your choice should also depend on which operation happens more often: adding/removing elements or accessing a single element directly. If it's the former, use a LinkedList. If it's the latter use an ArrayList.

Don't forget: when resizing the array (be it your own solution or Java's ArrayList) there is one point in time where twice the memory is allocated: once for the "old arry" and once for the "new array" right before the resize operation is finished.

So if memory is really your concern is something you should also think about.

like image 34
a_horse_with_no_name Avatar answered Dec 24 '22 02:12

a_horse_with_no_name