首页 > 代码库 > 性能比较
性能比较
java里面的链表可以添加索引,而C中的链表,是没有索引的
- package ArrayListVSLinkedList;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.LinkedList;
- /**
- * Created by IntelliJ IDEA.
- * User: luhba
- * Date: 13-7-6
- * 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,所以速度相当。那么再举一个差别最大
package jjj; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; 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(0,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(0,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(999999); ArrayListVSLinkedList.linkedList(999999); } }
性能比较
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。