public class Performancetester {
public static final int times=100000;
public static abstract class tester{
Private String operation;
Public Tester (String operation) {this.operation=operation;}
public abstract void Test (list<string> List);
Public String getoperation () {return operation;}
}
Static Tester iteratester=new Tester ("iterate") {//anonymous class to perform iterative operations
public void Test (list<string> List) {
for (int i=0;i<10;i++) {
Iterator<string> It=list.iterator ();
while (It.hasnext ()) {
It.next ();
}
}
}
};
Static Tester gettester=new Tester ("get") {//anonymous class to perform random access operations
public void Test (list<string> List) {
for (int i=0;i<list.size (); i++) {
for (int j=0;j<10;j++)
List.get (i);
}
}
};
Static Tester inserttester=new Tester ("Insert") {//anonymous class to perform insert operation
public void Test (list<string> List) {
Listiterator<string> It=list.listiterator (List.size ()/2);//start from the middle of the list
for (int i=0;i<times/2;i++) {
It.add ("Hello");
}
}
};
Static Tester removetester=new Tester ("remove") {//anonymous class to perform delete operation
public void Test (list<string> List) {
Listiterator<string> It=list.listiterator ();
while (It.hasnext ()) {
It.next ();
It.remove ();
}
}
};
static public void Testjavaarray (list<string> List) {
Tester[] Testers={iteratester,gettester};
Test (testers, list);
}
static public void Testlist (list<string> List) {
Tester[] Testers={inserttester,iteratester,gettester,removetester};
Test (testers,list);
}
private static void Test (tester[] testers, list<string> List) {
for (int i=0;i<testers.length;i++) {
System.out.print (testers[i].getoperation () + "Operation:");
Long T1=system.currenttimemillis ();
Testers[i].test (list);
Long T2=system.currenttimemillis ();
System.out.print (t2-t1+ "MS");
System.out.println ();
}
}
public static void Main (string[] args) {
List<string> List=null;
Testing the Java array
SYSTEM.OUT.PRINTLN ("----Test Java array----");
String[] Ss=new String[times];
Arrays.fill (SS, "Hello");
List=arrays.aslist (ss);
Testjavaarray (list);
Ss=new STRING[TIMES/2];
Collection<string> col=arrays.aslist (ss);
Test vector
SYSTEM.OUT.PRINTLN ("----test vector----");
List=new vector<string> ();
List.addall (COL);
Testlist (list);
Test LinkedList
SYSTEM.OUT.PRINTLN ("----test linkedlist----");
List=new linkedlist<string> ();
List.addall (COL);
Testlist (list);
Test ArrayList
SYSTEM.OUT.PRINTLN ("----test arraylist----");
List=new arraylist<string> ();
List.addall (COL);
Testlist (list);
}
}
Compare Java arrays, arraylist,linkedlist,vector performance comparison