Program: Timing Comparisons
New developers sometimes worry about the overhead of
these
collections and think they should use
arrays instead of data
structures. To investigate, I wrote a program that creates and
accesses 250,000 objects, once through a Java array and again through
an ArrayList
. This is a lot more objects than most
programs use. First the code for the Array
version:
import com.darwinsys.util.MutableInteger; /** Time a bunch of creates and gets through an Array */ public class Array { public static final int MAX = 250000; public static void main(String[] args) { System.out.println(new Array().run( )); } public int run( ) { MutableInteger list[] = new MutableInteger[MAX]; for (int i=0; i<list.length; i++) { list[i] = new MutableInteger(i); } int sum = 0; for (int i=0; i<list.length; i++) { sum += list[i].getValue( ); } return sum; } }
And the ArrayList
version:
import java.util.ArrayList; import com.darwinsys.util.MutableInteger; /** Time a bunch of creates and gets through an Array */ public class ArrayLst { public static final int MAX = 250000; public static void main(String[] args) { System.out.println(new ArrayLst().run( )); } public int run( ) { ArrayList list = new ArrayList( ); for (int i=0; i<MAX; i++) { list.add(new MutableInteger(i)); } int sum = 0; for (int i=0; i<MAX; i++) { sum += ((MutableInteger)list.get(i)).getValue( ); } return sum; } }
The Vector
-based version,
ArrayVec
, is sufficiently similar that I don’t feel the need to kill a tree reprinting ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.