Search code examples
javaperformancedata-structuresarraydeque

java array deque size vs performance


in my java code I suspect that the java.util.ArrayDeque size is affecting performance, but I wanted to confirm on here if that could be the case.

while (!otherClass.getDeque().isEmpty()){
  Trajectory t1 = otherClass.getDeque.remove();
  Runnable tr1 = new TrajectoryThread();
  Thread thread1 = new Thread(tr1);
  thread1.start();

if (!otherClass.getDeque().isEmpty()){
  Trajectory t2 = otherClass.getDeque.remove();
  Runnable tr2 = new TrajectoryThread();
  Thread thread2 = new Thread(tr2);
  thread2.start();

In my code, I remove a trajectory object if the deque is not empty and initiate a simulation on a new thread until 40 simulations are running concurrently. At the end of each simulation, there is a possibility of adding more trajectories to the queue. If there are trajectories still remaining on the queue after all simulations are finished the process repeats itself.

The operations I use are remove() , add(), isEmpty(), and also getting the Deque from another class. While timing each iteration, I find that for a Deque size of 4421 objects it takes 7756 miliseconds. While for a Deque size of 103 objects, it takes 43 miliseconds.


Solution

  • When encountering performance issues such as this, the right approach most of the time is to get good performance monitoring data before speculating on what part of your program is slow. You can use a tool like VisualVM to achieve this.

    If you are wondering if java.util.ArrayDeque operations are responsible for slowing down your program, then the answer is almost certainly no, because their execution time is largely dominated by the overhead of creating threads and running your simulations. ArrayDeques are very fast. They run the 3 operations you listed in your comment in constant time (more precisely, add runs in constant amortised time.); less theoretically, these operations are performed using low-level array manipulation which is very fast in practice. So I would not worry about that.

    On the other hand, if you're wondering in what way your execution time is related to the size of your problem, then we'll need more insights on what happens in your TrajectoryThreads.