ArrayList<Integer> is more costly than int[] in Java

16 Jul 2014

Yesterday I was having a great idea of instantiating an ArrayList once and re-use it instead of instantiate an array of int[] everytime.

It turns out that the performance is much worse. There are 2 points to note:

  1. ArrayList need to use Integer. This means boxing and un-boxing is performed on every get() and set()
  2. ArrayList.clear() sets all elements to null (so that GC can take care of it). It's costly

I think the right way is to declare a large int[] and re-use it, but then the size might not be big enough when there's a peak.

Anyway, I will just go with allocating int[] everytime. I only need like 300 to 1,000 elements at a time. It's the fastest way, it seems.