7

I am receiving XML and need to convert to either a primitive Array or ArrayList. Is there much difference in terms of performance in terms of memory and garbage collection? My application will be creating thousand of these objects every second and I need to minimize GC as I need real-time performance.

Thxs

DD.
  • 19,793
  • 49
  • 140
  • 237
  • 3
    This might answer your question: http://stackoverflow.com/questions/716597/array-or-list-in-java-which-is-faster – euphoria83 Oct 23 '11 at 21:09

4 Answers4

7

Primitive arrays are much more efficient, as they don't require wrapper objects. Guava has List implementations that are backed by primitive arrays (example: Ints.asList(int[])), perhaps that could be a reasonable solution for you: get the power of a collection but only use Objects when you actually need them.

Sean Patrick Floyd
  • 274,607
  • 58
  • 445
  • 566
3

Primitive arrays are always more efficient, but by how much depends on the exact details of your use case. I've recently sped up performance by a factor of 7, by ripping out the ArrayLists, and replacing them with primitive arrays, in the inner-most loops. The use case was an O(n^2) algorithm applied to lists 100-1000 characters long. I then did a controlled experiment, comparing the performance of a int[] array to a ArrayList, and interestingly, as the array/list sizes get bigger, the JIT compiler seems to kick in, and the performance penalty becomes a lot less (only ~20%). But for list sizes less than 500, the performance penalty of an ArrayList can be up to a factor of 10. So if you've got a frequently called method, which is manipulating lots of small lists or arrays (as was with my use case), using primitave arrays can have a big performance impact.

0

Linked lists are good for inserts/deletes, and arrays are good for random access.

salmanseifian
  • 843
  • 1
  • 6
  • 20
0

As Sean Patrick Floyd pointed out, primitive arrays are much more efficient. However, there are cases where one would definitely prefer Collections. But as long as you just iterate over the Objects, there is no need for Collections.

Oskar
  • 1,301
  • 9
  • 19