Codementor Events

Code inside - Improve the performance - session 2

Published May 21, 2021
Code inside - Improve the performance - session 2

The session 1 gave two problems to think and solve:

  1. What is code behind of the class and where we find it.
  2. Do we need to choose the another class to store our data (books, orders, customers) and what is the priorities to choose them.

Assume that ArrayList is chosen to store data. This session looks inside it:

Link 1: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
Link 2: http://developer.classpath.org/doc/java/util/ArrayList-source.html

From link 1, we notice:

  • Resizable-array: it is the normal array
  • Capacity: size of the array used to store the elements in the list. This can increased or reduced.
  • Not synchronized (no support the multi threads access)

From link 2, we notice:

  • private transient E[] data. We only to care about the array E[] where E is parameter of the array: ArrayList<Integer>, ArrayList<Book>,...
  • DEFAULT_CAPACITY = 10: the user can provice capacity; otherwise value 10 is used

Some methods that make the program's performance becomes bad:

  • indexOf(Object e) or lastIndexOf: use the for loop: "for (int i = 0; i < size; i++)"
  • ensureCapacity(): expand the array, call System.arraycopy (this method takes time to copy)
  • add(E e): call ensureCapacity(size + 1) that can extend the array
  • contains(Object e): call indexOf method
  • remove(): call System.arraycopy (this method takes time to copy)

Some methods are fast:

  • get(int index): go directly to the specific address (offset) and retrieve it.

We can see that Array is very fast in getting the elements based on the index.
The performance is bad in insert, search, remove.

In the example program, book is not retrieved by the index. So ArrayList is not suitable to use in this case.

Next think: Which data structure should be used in order to replace the ArrayList?

*** Thank you for reading - Keep study hard ***

(*) Cover photo is retrieved from https://www.raconteur.net/wp-content/uploads/2021/03/transform-fast.jpg

Discover and read more posts from An Phung Duy
get started
post commentsBe the first to share your opinion
Cleopatra Calantha
3 years ago

Perfect entertainment theme.
Listen to online radio stations at the site: https://internetradiohoren.de/

eero dekari
3 years ago

Am interesting to learn these languages
https://downloadnox.onl/ https://vidmate.cool/ https://vlc.onl/

Show more replies