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
Array is a fixed length data structure whereas ArrayList is a variable length Collection class. We cannot change length of array once created in Java but ArrayList can be changed. We cannot store primitives in ArrayList, it can only store objects.
An array is faster and that is because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows. It creates a new Array and copies every element from the old one to the new one.
The ArrayList class implements a growable array of objects. ArrayList cannot hold primitive data types such as int, double, char, and long. With the introduction to wrapped class in java that was created to hold primitive data values.
1) First and Major difference between Array and ArrayList in Java is that Array is a fixed-length data structure while ArrayList is a variable-length Collection class. You can not change the length of Array once created in Java but ArrayList re-size itself when gets full depending upon the capacity and load factor.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With