1

In this Question I read the following:

If you're doing comparatively few operations, ie less than 1000 or so enqueue/dequeues in total, then an array would be faster because it is contiguous in memory.

My question is: How caching an ArrayList works in Java? Are there cases, when an ArrayList implemented Queue or Stack perform better then a LinkedList implemented in Java?

Community
  • 1
  • 1
codeme
  • 861
  • 2
  • 12
  • 29

1 Answers1

1

hen an ArrayList implemented Queue or Stack perform better then a LinkedList implemented in Java?

When the queue is almost always empty or with 1 element, ArrayList is faster and creates less garbage (ie none)

If you have a fast consumer, it will almost always consumer what ever the producer produces as it produces it. This means there is typically 0 or 1 elements in the queue. Under these conditions ArrayList is faster as it doesn't create any objects or produce garbage.

BTW ArrayDeque is a better choice because this performs well even if there is more than 1 element.

How caching an ArrayList works in Java?

There is nothing special about the way the CPU caches accesses to an ArrayList.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • If a Queue or a Stack is almost empty or with 1 element, we can call that an Arraylist,or basically whatever we want because, we will just add and remove with an Array, the order of that is irrelevant. Am I right, or missing something? – codeme Apr 21 '16 at 20:03
  • 1
    @codeme it's more the point that ArrayList is slow except when adding/removing the last element, in which case it is faster than Linkedlist. – Peter Lawrey Apr 21 '16 at 20:14