In production I will have to populate pretty large collection of string (containing about 100M strings). I don't need to iterate through it, just populate and leave it as is.
I will have to persists it, but it's the responsibility of another thread.
I thought it was more efficient to populate LinkedList
than ArrayList
.
Here is the simple program:
public static void main(String[] args) {
long start2 = System.nanoTime();
Collection<String> col = new ArrayList<>(); // <---HERE
for (long i = 0; i < 100000000; i++) {
col.add(String.valueOf(i));
if (i % 1000000 == 0)
System.out.println(i);
}
long end2 = System.nanoTime();
System.out.println(end2 - start2);
System.out.println(col.hashCode() == System.nanoTime());
}
For ArrayList
the average result is: 61535592462
But if I replace it with LinkedList
the program does not even finish. It always stops at 84000000
.
Why that? Could you explain potential cause for these behavior? Is it platform-specific?
I use Ubuntu 16.04
+ java 8
.
UPD: After pretty long time, the program with LinkedList finshes with this:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.LinkedList.linkLast(LinkedList.java:142)
at java.util.LinkedList.add(LinkedList.java:338)
at com.test.App.main(App.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)