I would think that inserting into a LinkedList should be faster than inserting into an ArrayList because inserting into a LinkedList just requires copying references whereas inserting into an ArrayList requires creating a bunch of new arrays in addition to copying references. But I created Java code to test this and I found the opposite, that inserting into an ArrayList is faster than inserting into a LinkedList.
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
class ListPerformanceTester {
public static void main(String[] args) {
System.out.println("Time to perform ten million insertions using LinkedList: " +
timeToPerformTenMillionInsertionsUsing(new LinkedList<>()));
System.out.println("Time to perform ten million insertions using ArrayList: " +
timeToPerformTenMillionInsertionsUsing(new ArrayList<>()));
}
private static long timeToPerformTenMillionInsertionsUsing(List<String> list) {
Instant start = Instant.now();
for (int i = 0; i < 10000000; ++i) {
list.add("");
}
return Duration.between(start, Instant.now()).toMillis();
}
}
Results from running three times:
Time to perform ten million insertions using ArrayList: 135
Time to perform ten million insertions using LinkedList: 1321
Time to perform ten million insertions using ArrayList: 126
Time to perform ten million insertions using LinkedList: 1094
Time to perform ten million insertions using ArrayList: 125
Time to perform ten million insertions using LinkedList: 1086
I even tried reversing the order of the inserts just in case that had an effect and LinkedList still took longer:
Time to perform ten million insertions using LinkedList: 2642
Time to perform ten million insertions using ArrayList: 402
Why is inserting into an ArrayList faster than inserting into a LinkedList?
$ java -version
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)