A site devoted mostly to everything related to Information Technology under the sun - among other things.

Tuesday, October 1, 2019

Execution Speeds of Java Collections

Execution Speeds of Java Collections - List/for, Array/for, List/foreach, Array/foreach

===Results==

List/for 3697
Array/for 1548
List/foreach 5654
Array/foreach 5659

===Code====

List list = new ArrayList(); Integer[] arr = new Integer[6000000]; Random rand = new Random(12345); for (int i = 0; i < 6000000; i++) { list.add(rand.nextInt(5000)); arr[i] = rand.nextInt(); } int chk = 0; Stopwatch watch = new Stopwatch(); watch.start(); for (int rpt = 0; rpt < 100; rpt++) { int len = list.size(); for (int i = 0; i < len; i++) { chk += list.get(i); } } watch.stop(); System.out.println("List/for: " + watch.elapsedMillis()); chk = 0; watch = watch.reset(); watch = watch.start(); for (int rpt = 0; rpt < 100; rpt++) { for (int i = 0; i < arr.length; i++) { chk += arr[i]; } } watch.stop(); System.out.println("Array/for: "+ watch.elapsedMillis()); chk = 0; watch = watch.reset(); watch = watch.start(); for (int rpt = 0; rpt < 100; rpt++) { for(Integer i: list) { chk += i; } } watch.stop(); System.out.println("List/foreach: " + watch.elapsedMillis()); chk = 0; watch = watch.reset(); watch = watch.start(); for (int rpt = 0; rpt < 100; rpt++) { for(Integer i: list) { chk += i; } } watch.stop(); System.out.println("Array/foreach: " + watch.elapsedMillis());

No comments:

About Me

My photo
I had been a senior software developer working for HP and GM. I am interested in intelligent and scientific computing. I am passionate about computers as enablers for human imagination. The contents of this site are not in any way, shape, or form endorsed, approved, or otherwise authorized by HP, its subsidiaries, or its officers and shareholders.

Blog Archive