DD.
DD.

Reputation: 21981

Is there a big difference in terms of performance between the primitive Array and an ArrayList?

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.

Upvotes: 7

Views: 10852

Answers (4)

salmanseifian
salmanseifian

Reputation: 1082

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

Upvotes: 0

Chess Cardigan
Chess Cardigan

Reputation: 31

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.

Upvotes: 3

Oskar
Oskar

Reputation: 1331

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.

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298858

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.

Upvotes: 7

Related Questions