1、 ArrayList和LinkedList插入元素性能差别
ArrayList内部使用数组存储,针对这一性质,在数组最后插入元素较快,在数组中间插入元素较慢,因为插入位置之后的元素要后移。而LinkedList在哪个位置插入都比较快,当然在LinkedList中间位置插入时,也涉及到遍历时间,但是该时间比较短。下面是测试。
测试一:插入到最后位置,性能差别不大
package com.pcitc.pattern.collection;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class ArryListClient {
/**
* @param args
*/
public static void main(String[] args) {
List<UserBean> list = new ArrayList<UserBean>();
List<UserBean> linkedlist = new LinkedList<UserBean>();
int count = 100000;
System.out.println("run...");
UserBean ub = null;
long i1 = System.currentTimeMillis();
for(int i = 0;i<count;i++){
ub = new UserBean(""+i,i,"ddd"+i);
list.add(i,ub);
}
long i2 = System.currentTimeMillis();
System.out.println("增加元素,Arraylist耗时:" + (i2-i1));
long i3 = System.currentTimeMillis();
for(int i = 0;i<count;i++){
ub = new UserBean(""+i,i,"ddd"+i);
linkedlist.add(0,ub);
}
long i4 = System.currentTimeMillis();
System.out.println("增加元素,linkedlist耗时:" + (i4-i3));
list.clear();
linkedlist.clear();
list = null;
linkedlist = null;
}
性能一运行结果:
run...
增加元素,Arraylist耗时:219
增加元素,linkedlist耗时:141
测试二:插入到首位置,性能差别大
package com.pcitc.pattern.collection;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class ArryListClient {
/**
* @param args
*/
public static void main(String[] args) {
List<UserBean> list = new ArrayList<UserBean>();
List<UserBean> linkedlist = new LinkedList<UserBean>();
int count = 100000;
System.out.println("run...");
UserBean ub = null;
long i1 = System.currentTimeMillis();
for(int i = 0;i<count;i++){
ub = new UserBean(""+i,i,"ddd"+i);
list.add(0,ub);
}
long i2 = System.currentTimeMillis();
System.out.println("增加元素,Arraylist耗时:" + (i2-i1));
long i3 = System.currentTimeMillis();
for(int i = 0;i<count;i++){
ub = new UserBean(""+i,i,"ddd"+i);
linkedlist.add(0,ub);
}
long i4 = System.currentTimeMillis();
System.out.println("增加元素,linkedlist耗时:" + (i4-i3));
list.clear();
linkedlist.clear();
list = null;
linkedlist = null;
}
}
性能二运行结果:性能差36倍之多
run...
增加元素,Arraylist耗时:6250
增加元素,linkedlist耗时:234