piątek, lutego 17, 2017

Czy ArrayList jest szybsze od LinkedList?

int elements = 1000000;
int tries = 100;
String values[] = new String[elements];
for (int k=0; k < elements; k++) {
 values[k] = String.valueOf(k).intern();
}
  
long t0 = System.currentTimeMillis();
for (int i=0; i < tries; i++) {
 ArrayList al = new ArrayList();
 for (int j=0; j < elements; j++)
  al.add(values[j]);
}
  
long t1= System.currentTimeMillis();
for (int i=0; i < tries; i++) {
 LinkedList ll = new LinkedList();
 for (int j=0; j < elements; j++)
  ll.add(values[j]);
}
  
long t2 = System.currentTimeMillis();
System.out.println("Add to ArrayList: "+(t1-t0)/100+" ms avg, cnt="+elements+", tries="+tries);
System.out.println("Add to LinkedList: "+(t2-t1)/100+" ms avg, cnt="+elements+", tries="+tries);
--
Add to ArrayList: 33 ms avg, cnt=2000000, tries=100
Add to LinkedList: 51 ms avg, cnt=2000000, tries=100

Add to ArrayList: 18 ms avg, cnt=1000000, tries=100
Add to LinkedList: 12 ms avg, cnt=1000000, tries=100

0 komentarze: