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:
Post a Comment