piątek, lutego 17, 2017

Czy ArrayList jest szybsze od LinkedList? #2

ArrayList al = new ArrayList<>();
for (int j=0; j < elements; j++)
 al.add(new Long(j));
LinkedList ll = new LinkedList<>();
for (int j=0; j < elements; j++)
  ll.add(new Long(j));
int indices[] = new int[elements / 100];
Random r = new Random(19700101);
for (int i=0; i < indices.length; i++) {
 indices[i] = r.nextInt(indices.length);
}
 
t0 = System.currentTimeMillis();
BigDecimal sum = new BigDecimal(0);
for (int i=0; i < indices.length; i++) {
 sum.add( new BigDecimal(al.get(indices[i])) );
}
t1 = System.currentTimeMillis();
sum = new BigDecimal(0);
for (int i=0; i < indices.length; i++) {
 sum.add( new BigDecimal(ll.get(indices[i])) );
}
t2 = System.currentTimeMillis();
  
System.out.println("Access ArrayList: "+(t1-t0)+" ms, cnt="+elements+", tries="+indices.length);
System.out.println("Access LinkedList: "+(t2-t1)+" ms, cnt="+elements+", tries="+indices.length);

--
Access ArrayList: 12 ms, cnt=2000000, tries=20000
Access LinkedList: 371 ms, cnt=2000000, tries=20000

0 komentarze: