ArraryList 和 LinkedList 如何选择?

来源:互联网 发布:淘宝店招图片怎么做 编辑:程序博客网 时间:2024/05/29 17:23

开门见山吧,ArraryList和LinkedList都是集成于List的,符合list的基本大的特性。

集合(list)与数组的区别:
1.集合长度不固定,数组长度固定;换句话说,集合是动态的,数组是静态的。(重点)
2.集合可以指定下标索引,并且会自动给插入位置向后挪位置,而不是像数组那样覆盖。


一般使用场景:

       定义list对象,然后保存服务器访问的数据,然后显示到listview或者recyleView上面。。。。

       上面过程需要add添加到list,然后显示时候从list 中get出来。。。

遇到疑问:

      按照ArraryList 和 LinkedList特性,,,发现ArraryList 以数组数据结构方式保存,LinkedList以数据链表方式保存、。。。上面的场景遇到问题了,既要add也需要get,这样的话,哪个都不适合了。。。

     现在如何抉择使用哪个呢? (先提出问题,后面有答案)

遇到这样的问题,我就想到掌握的这些概念都是出于理论层面,没有从实际代码性能中查看,到底差距有多大,下面就已实际代码性能上面分析问题,然后看看add的性能差距多大,get的性能差距多大,然后作为我们选择使用的一个参考。。。

    1. add 性能测试代码如下(结果可能与手机和手机当前性能有关):

list = new ArrayList();list2 = new LinkedList();int  num = 1000000;long currentTimestart = System.currentTimeMillis();for(int i=0; i<num; i++){    list.add(i+"");}long currentTimeend = System.currentTimeMillis();Toast.makeText(MainActivity.this,"test1:"+(currentTimeend-currentTimestart)+"",Toast.LENGTH_SHORT).show();
long currentTimestart2 = System.currentTimeMillis();for(int i=0; i<num; i++){    list2.add(i+"");}long currentTimeend2 = System.currentTimeMillis();Toast.makeText(MainActivity.this,"test2:"+(currentTimeend2-currentTimestart2)+"",Toast.LENGTH_SHORT).show();

测试结果(单位:毫秒ms):ArraryList test1: 568,620,609,507,508…………(当然还有很多数据,就不一一列举了)

测试结果(单位:毫秒ms):LinkedList test2: 909,794,697,698,535…………(当然还有很多数据,就不一一列举了)


得出结论:

哇塞,,,怎么回事呢? 对于ArraryList和LinkedList add性能从概念上是有差距,但是100000条数据,发现差距不太明显呀。。。

     

       2. get 性能测试代码如下(结果可能与手机和手机当前性能有关):


int  num = 1000000;

long currentTimestart = System.currentTimeMillis();for(int i=0; i<num; i++){    String numf  = list.get(i);}long currentTimeend = System.currentTimeMillis();Toast.makeText(MainActivity.this,"test1:"+(currentTimeend-currentTimestart)+"",Toast.LENGTH_SHORT).show();long currentTimestart2 = System.currentTimeMillis();for(int i=0; i<num; i++){    list2.get(i);}long currentTimeend2 = System.currentTimeMillis();Toast.makeText(MainActivity.this,"test2:"+(currentTimeend2-currentTimestart2)+"",Toast.LENGTH_SHORT).show();


测试结果(单位:毫秒ms):ArrayListtest1: 44,67,80,43,42…………(当然还有很多数据,就不一一列举了)

测试结果(单位:毫秒ms):LinkedList test2: 直接出现ANR问题,没出现结果


得出结论:

         对于ArraryList 和LinkedList,add和get差距是有的,但从上面的测试结果可以得出,

         1. add差距其实没那么大,可能LinkedList数据结果是链表的,但是底层应该做了优化。

         2.get差距太大了,ArraryList使用50ms左右,LinkedList出现ANR问题,这就是很明显差异。

        还有就是,我觉得书上说的肯定是对的,但是自己亲自测试,也许会发现更多深刻的东西,通过这个过程,自己也可以学习一些新的东西,对自己也是一个提升。这也就是“蝴蝶效应”吧




0 0