java - Filling ArrayList vs LinkedList -



java - Filling ArrayList vs LinkedList -

i have been thinking linkedlist fills faster arraylist. know arraylist based on simple array limited length(constant). every time array out of range, new array higher range created. linkedlist much simpler. hasn't got limit (except memory), should filled faster. run next code:

public static void main(string[] args) { int length = 7000000; list<integer> list = new linkedlist<integer>(); long oldtime = system.currenttimemillis(); (int = 0; < length; i++) { list.add(i); } system.out.println("linkedlist fill: " + (system.currenttimemillis() - oldtime)); list = new arraylist<integer>(); oldtime = system.currenttimemillis(); (int = 0; < length; i++) { list.add(i); } system.out.println("arraylist fill: " + (system.currenttimemillis() - oldtime)); }

the output is:

linkedlist fill: 3936 arraylist fill: 628

why so?

you can't benchmark performance in java. see how write right micro-benchmark in java? more detailed explanations of many things can go wrong.

if test code jmh next results:

benchmark mode samples score error units c.a.p.so26404256.arraylist avgt 5 7.661 ± 0.672 ms/op c.a.p.so26404256.linkedlist avgt 5 9.675 ± 1.213 ms/op

so filling linkedlist seems slower filling arraylist, difference lot less test indicated.

as reason difference, because each element of linkedlist wrapped in node: means more object creations , more garbage collections. , penalty due array copies in arraylist less think because highly optimised.

java arraylist linked-list performance-testing microbenchmark

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -