Reputation: 2300
Java does not let us create ArrayList
of primitives directly. But we can create a ArrayList
of the primitives wrapper class.
But when accessing the primitive value , compiler automatically does the wrapping and unwrapping. Is this not an overhead ? My question is what are performance implications of this ?
In such a case wouldn't int[]
perform better than ArrayList<Integer>
?
Has anyone measured performance of int[]
vs ArrayList<Inetger>
for Java5.0
(when this was first introduced) and latter versions of Java. It would be really helpful for everybody who runs into this question , if you could share the test results.
Upvotes: 2
Views: 889
Reputation: 6706
The primitive collections in libraries like Eclipse Collections, FastUtil, Trove, HPPC, will save you memory and will often perform better than their boxed equivalents in Java. Each of the libraries will provide a richer set of methods than int[]
. It is best for you to compare performance based on your specific use cases.
I found this Baeldung article titled a "Performance Comparison of Primitive Lists in Java" which compares FastUtil, Trove and Colt primitive lists.
The Eclipse Collections open source library has several primitive collections including List
, Set
, Bag
, Stack
and Map
supporting all primitive types. There have been a few articles written with performance benchmarks comparing performance of JDK Collections with Eclipse Collections primitive collections.
The NatTable article has some comparisons between int[]
and List<Integer>
.
Note: I am a committer for Eclipse Collections
Upvotes: 2
Reputation: 3117
A question was asked on the same topic with the following benchmark results on a 20M elements int[]
vs. ArrayList
(which I re-run on my computer, from @Wsl_F question):
public static void main(String[] args) {
int n = 20_000_000;
System.out.println("Warming up...");
list(n);
array(n);
long t0 = System.nanoTime();
int v = list(n);
t0 = System.nanoTime() - t0;
System.out.printf("list %.1f ms (%d)\n", (t0 / 1000000.0), v);
t0 = System.nanoTime();
v = array(n);
t0 = System.nanoTime() - t0;
System.out.printf("array %.1f ms (%d)\n", (t0 / 1000000.0), v);
}
private static int list(int n) {
ArrayList<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(i);
return list.get(n/2);
}
private static int array(int n) {
int[] list = new int[n];
for (int i = 0; i < n; i++)
list[i] = i;
return list[n/2];
}
Gives me (Eclipse on Ubuntu 16.04 x64 with Intel Core i7):
list 1839,9 ms (10000000)
array 515,9 ms (10000000)
Upvotes: 0