0

LinkedList is faster in add element. But ArrayList is better in stored data.

I suppose that I will have 1 million elements to add to the List. Then I will use method saveAll() to save them in DB. Code like below:

//ArrayList
List<Person> personList = new ArrayList<>();
fullPersonList.forEach(item -> {
    if (item.isMale())
        personList.add(item);
});
personRepository.saveAll(personList);

//LinkedList
List<Person> personList = new LinkedList<>();
fullPersonList.forEach(item -> {
    if (item.isMale())
        personList.add(item);
});
personRepository.saveAll(personList);
Dr Mido
  • 2,414
  • 4
  • 32
  • 72
Jay
  • 11
  • 3
  • 1
    Faster in which aspect, adding elements to the list, or the subsequent iteration of the list? – Chaosfire Sep 10 '22 at 12:27
  • They way you use them, they would perform the same. – Cheng Thao Sep 10 '22 at 16:31
  • 2
    JPA tends to write to databases and thus to disks. The performance of *that* write will severely outweigh any performance difference you could have between `ArrayList` and `LinkedList`, so forget about it. Also: forget about `LinkedList´, there's no good reason to ever use it. [Even the creator agrees](https://twitter.com/joshbloch/status/583813919019573248). – Joachim Sauer Sep 10 '22 at 21:05
  • There are complicated secondary effects due to garbage collection and memory locality which will affect `ArrayList` and `LinkedList` differently. Especially for large lists. Also, if you can set the correct *capacity* of the `ArrayList` it will be a lot more efficient than a `LinkedList`; i.e. "LinkedList is faster in add element" won't be true. – Stephen C Sep 11 '22 at 03:54
  • Frankly, this question has the whiff of *premature optimization*. – Stephen C Sep 11 '22 at 03:55
  • As a basic rule of thumb, in almost all cases, ArrayList is actually faster than LinkedList, so use ArrayList, unless you have proven that LinkedList is faster for your use case. – Mark Rotteveel Sep 11 '22 at 15:39

1 Answers1

0

It would be better seeing the definition of personRepository.saveAll(personList)

Regardless, ArrayList internally uses an array. I expect a read operation to be hence faster, so I'd go with the ArrayList

see linked_list_implementation here

NightStorm
  • 101
  • 12