性能比较
Posted 多情剑客无情剑;
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了性能比较相关的知识,希望对你有一定的参考价值。
通过index获取元素的值
java里面的链表可以添加索引,而C中的链表,是没有索引的
- package ArrayListVSLinkedList;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.LinkedList;
- ArrayList和LinkedList向后追加元素的性能比较
- /**
- * Created by IntelliJ IDEA.
- * User: luhba
- * Date: 17-8-10
- * Time: 下午7:06
- * To change this template use File | Settings | File Templates.
- */
- public class ArrayListVSLinkedList
- {
- public static void ArrayListTest(long num)
- {
- ArrayList list = new ArrayList() ;
- long berforeTime= new Date().getTime();
- for(int i=0;i<num;i++)
- {
- list.add(i,i);
- }
- long afterTime = new Date().getTime();
- System.err.println("The process ArrayListTest used a total time is "+(afterTime-berforeTime) +" millisecondes !" );
- }
- public static void linkedList(long num)
- {
- LinkedList list = new LinkedList();
- long berforeTime= new Date().getTime();
- for(int i=0;i<num;i++)
- {
- list.add(i,i);
- }
- long afterTime = new Date().getTime();
- System.err.println("The process linkedList used a total time is "+(afterTime-berforeTime) +" millisecondes !" );
- }
- public static void main(String[] args)
- {
- ArrayListVSLinkedList.ArrayListTest(100000);
- ArrayListVSLinkedList.linkedList(100000);
- }
- }
执行的结果是:
The process ArrayListTest used a total time is 31 millisecondes !
The process linkedList used a total time is 32 millisecondes !
这个是为什么呢?顺序存储插入的速度竟然比链式存储的还要快?
答:这个例子是顺序存储的最理想的方式,不用向后移动一个element,所以速度相当。那么再举一个差别最大
//数组和链表在头部插入数据的效率
import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; public class Hi{ public static void ArrayListTest(long num){ List list = new ArrayList() ; long berforeTime= new Date().getTime(); for(int i=0;i<num;i++){ //在数组的头部插入一个元素 list.add(0,i); } long afterTime = new Date().getTime(); System.err.println("The process ArrayListTest used a total time is "+(afterTime-berforeTime) +" millisecondes !" ); long t1= new Date().getTime(); while(!list.isEmpty()){ while(!list.isEmpty()){ list.remove(0); } } long t2 = new Date().getTime(); System.err.println("数组删除"+(t2-t1)); } public static void linkedList(long num){ List list = new LinkedList(); long berforeTime= new Date().getTime(); for(int i=0;i<num;i++) { list.add(0,i); /*添加元素:添加单个元素 如果不指定索引的话,元素将被添加到链表的最后*/ } long afterTime = new Date().getTime(); System.err.println("The process linkedList used a total time is "+(afterTime-berforeTime) +" millisecondes !" ); long t1= new Date().getTime(); while(!list.isEmpty()){ list.remove(0); } long t2 = new Date().getTime(); System.err.println("链表删除"+(t2-t1)); } public static void main(String[] args){ Hi.ArrayListTest(99999*5); Hi.linkedList(99999*5); } }
以上是关于性能比较的主要内容,如果未能解决你的问题,请参考以下文章