0

In my code, I have been querying a list of 10k items using findAll of repository.

There is only one List reference to which I assign the result of findAll then run a loop for the items of List.

Total records in DB are usually few times of 10K i.e. loop currently iterates somewhere between 6 - 12 times.

What I observed is that successive processing in that loop starts taking more time after around 20K read items or so.

Instead of assigning reference if I use List.addAll() for findAll items and before adding next chunk of items, I clear out list using List.clear() then execution time of iteration remains constant & doesn't increase successively.

Code with iteration increasing time,

while(condition){
  List<T> reference = repo.findAll()
  for(T t:reference){
   //Processing 
  }
  //Check Condition if its false
}

Constant Time ,

List<T> reference = new ArrayList<>();
while(condition){
  reference.addAll(repo.findAll())
  for(T t:reference){
   //Processing 
  }
reference.clear();
//Check Condition if its false
}

Not sure why the gap as objects should be garbage collected in first instance too ?

Related question - list.clear() vs list = new ArrayList()

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
  • I assume that this has something to do with increasing the ArrayList. Read more about that topic here: https://medium.com/@malith.jayasinghe/a-performance-evaluation-of-java-arraylist-f097582b5c4d – Simon Martinelli Sep 27 '18 at 11:48
  • "starts taking more time..." What are the *actual* measurements you took, and how did you take them? – Michael Sep 27 '18 at 12:00
  • @Michel : I just logged loop iteration time using `System.currentTimeMillis()` . Its like for first 10k items, iteration time is in the range of 100ms then in next few iterations it starts going upto 300 ms & then in next few upto 500 ms so on. – Sabir Khan Sep 27 '18 at 12:53
  • will not `reference.clear();` itself add a few milliseconds to the iteration time? – S.K. Sep 27 '18 at 12:54
  • @S.K. Yep, thats whats is logical & is in linked QA too. Just noticed the behavior so put the question. – Sabir Khan Sep 27 '18 at 13:44

1 Answers1

-1

The first way throws away allocated backing arrays every loop, which will waste much of time to GC and reallocate spaces.

However, the second reuses the backing array and reduces GC & reallocating time.

Refer to: Why ArrayList.clear() method doesn't free memory?

terry.qiao
  • 1,959
  • 2
  • 8
  • 10