zoukankan      html  css  js  c++  java
  • Java学习笔记(1)----规则集和线性表性能比较

      为了比较 HashSet,LinkedHashSet,TreeSet,ArrayList,LinkedList 的性能,使用如下代码来测试它们加入并删除500000个数据的时间:

    package src;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.LinkedHashSet;
    import java.util.LinkedList;
    import java.util.TreeSet;
    
    
    
    
    public class Solution {
    
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Collection<Integer>set1=new HashSet<Integer>();
            System.out.println("Time for hash set is "+getTestTime(set1,500000)+" milliseconds");
            
            Collection<Integer>set2=new LinkedHashSet<Integer>();
            System.out.println("Time for linked hash set is "+getTestTime(set2, 500000)+" milliseconds");
            
            Collection<Integer>set3=new TreeSet<Integer>();
            System.out.println("Time for tree set is "+getTestTime(set3, 500000)+" milliseconds");
            
            Collection<Integer>set4=new ArrayList<Integer>();
            System.out.println("Time for arraylist is "+getTestTime(set4, 500000)+" milliseconds");
            
            Collection<Integer>set5=new LinkedList<Integer>();
            System.out.println("Time for linked list is "+getTestTime(set5, 500000)+" milliseconds");
            
            System.out.println("
    Game Over!");
        }
        
        public static long getTestTime(Collection<Integer>c,int size){
            long startTime=System.currentTimeMillis();
            List<Integer>list=new ArrayList<Integer>();
            for(int i=0;i<size;i++){
                list.add(i);
            }
            
            Collections.shuffle(list);
            for(int ele:list){
                c.add(ele);
            }
            
            Collections.shuffle(list);
            
            for(int ele:list){
                c.remove(ele);
            }
            
            long endTime=System.currentTimeMillis();
            return endTime-startTime;
        }
    }

    运行结果如下:

    Time for hash set is 372 milliseconds
    Time for linked hash set is 404 milliseconds
    Time for tree set is 936 milliseconds
    Time for arraylist is 200759 milliseconds
    Time for linked list is 473436 milliseconds
    
    Game Over!

    可以看到,速度由快到慢依次是:HashSet,LinkedHashSet,TreeSet,ArrayList,LinkedList。

  • 相关阅读:
    Android应用查看本地数据库
    C#导出和导入Excel模板功能
    数据库事务的四种隔离模式
    .NET进阶篇-丑话先说,Flag先立--致青春
    博客的第一天:回顾半年前的基础:SQL--基础查询+年月日格式+拼接
    【MySQL】你以为设置了并行复制就降低延迟了?这个你绝对想不到!
    中秋的月亮
    细看国产数据库,从根上知道如何学习?
    开篇2019
    Mysql学习笔记整理之数据库优化
  • 原文地址:https://www.cnblogs.com/dongling/p/5741709.html
Copyright © 2011-2022 走看看