您的位置:首页 > 编程语言 > Java开发

测试java的ArrayList与LinkedList的性能

2015-04-13 19:02 330 查看
二把刀真是误事,我对数据结构了解不多,在用ArrayList与LinkedList的时候我曾经倾向用LinkedList,以为链表就方便插入,后来做一个实验。

代码:

public class ListEfficiencyTest {

public static void main(String[] args) {

int count = 10000;

long begin1 = System.nanoTime();

ArrayList<String> arraylist = new ArrayList<String>();

for(int i=0;i<count;i++){

arraylist.add("test");

}

long end1 = System.nanoTime();

System.out.println("ArrayList add "+count+" String, costs time "+(end1-begin1));

begin1 = System.nanoTime();

for(int i=0;i<arraylist.size();i++){

arraylist.get(i);

}

end1 = System.nanoTime();

System.out.println("ArrayList get(index) "+count+" String, costs time "+(end1-begin1));

begin1 = System.nanoTime();

Iterator<String> it1 = arraylist.iterator();

while(it1.hasNext()){

it1.next();

}

end1 = System.nanoTime();

System.out.println("ArrayList iterator "+count+" String, costs time "+(end1-begin1));

long begin2 = System.nanoTime();

LinkedList<String> linkedlist = new LinkedList<String>();

for(int i=0;i<count;i++){

linkedlist.add("test");

}

long end2 = System.nanoTime();

System.out.println("LinkedList add "+count+" String, costs time "+(end2-begin2));

begin2 = System.nanoTime();

for(int i=0;i<linkedlist.size();i++){

linkedlist.get(i);

}

end2 = System.nanoTime();

System.out.println("LinkedList get(index) "+count+" String, costs time "+(end2-begin2));

begin2 = System.nanoTime();

Iterator<String> it = linkedlist.iterator();

while(it.hasNext()){

it.next();

}

end2 = System.nanoTime();

System.out.println("LinkedList iterator "+count+" String, costs time "+(end2-begin2));

}

}

用相同量的数据测试ArrayList与LinkedList的插入耗时、索引取值、Iterator迭代取值的耗时,结果如下:

 10000
 插入耗时根据index遍历耗时根据iterator迭代遍历耗时
ArrayList129020912965613139019
LinkedList2836015614847862747069
 100000
 插入耗时根据index遍历耗时根据iterator迭代遍历耗时
ArrayList655269510380325426695
LinkedList1274032096730230612598010
 1000000
 插入耗时根据index遍历耗时根据iterator迭代遍历耗时
ArrayList48045603598236447055954
LinkedList243645601143263362527515298744
耗时均为毫微秒数:

1秒=1000豪秒 1毫秒=1000微秒 1微秒=1000毫微秒

1毫微秒=1纳秒 1纳秒=10埃秒

数值都是毫微秒, 1秒=1000毫秒*1000微秒=1000000毫微秒
现象:

1、同样多的数据,LinkedList的耗时反倒更大。

2、进行index索引遍历时,数据量越大,LinkedList的效率就越更低。

3、在使用Iterator进行遍历集合内容时,LinkedList的的效率更优,但是优势不明显。

结论:

以后尽量用ArrayList了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: