简体   繁体   中英

Memory and performance of Java Arraylist

I have written Java code to get the list of employee name from database and storing it in a list.

List<String> employeeList = new ArrayList<Integer>();
employeeList = getAllEmployee();

My database changes regularly and number of employees increases or decreases daily.

Normally logic what can I use is getcount from DB and create Arraylist from that count.

I have a thought. Now if I have 3 employee from DB, If I create Arraylist I will create initial capacity of 10. Is there any way to remove the unused space 7 from ArrayList. Also please enlighten me on initial capacity algorithm and load factor too.

i think this is what you are looking for java.util.ArrayList.trimToSize() method , that trims the capacity of an ArrayList instance to the current size. it will minimize the storage of an ArrayList instance

doclink

Yes, there is a way to remove the unused space. You can use the method trimToSize() , which, according to its Javadoc,

trims the capacity of this ArrayList instance to be the list's current size.

Note that this requires downcasting a List to an ArrayList , by the way.

The current implementation of ArrayList in Oracle's Java 8 runtime has a private method grow() . You can see the implementation if you have a JDK installed, I suppose. It doesn't work with a 'load factor' but uses a different algorithm for determining the new capacity of the underlying array:

int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);

Plus it does some boundary checking to make sure the int s do not overflow, but that's a different story.

You can create a list with a size equals to the desired size.

List<String> list = new ArrayList<String>(desiredSize);

Please note that the code you wrote

List<String> employeeList= new arrayList()<Integer>;
employeeList= getAllEmployee();

probabilly create two lists. One explicitly, the second inside the code of getAllEmployee() . So the best is

List<String> employeeList = getAllEmployee() 

and in your getAllEmployee code do something like that

public List<String> getAllEmployee() {
    ...
    int desiredSize = ....
    ...
    List<String> list = new ArrayList<String>(desiredSize);
    ...
    return list;
}

Note that if you are not in an extremely optimized environment (and I think you aren't otherwise you didn't asked for this kind of problem) it is not necessary to save few bytes. If the code is less readable and you have to calculate the desired size with an additional call to the database is not a good programming choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM