listperformance.java

来自「Java程序设计技巧与开发实例附书源代码。」· Java 代码 · 共 69 行

JAVA
69
字号

import java.util.*;

public class ListPerformance
{
    public static long addRemove(List list, int n)
    {
        long start = System.currentTimeMillis();
        for (int i = 0; i < n; i++)
        {
            list.add(new Double(i));
        }
        for (int i = 0; i < n; i++)
        {
            list.remove(0);
        }
        return (System.currentTimeMillis() - start);
    }

    public static long jumpAround(List list, int n)
    {
        long start = System.currentTimeMillis();
        for (int i = 0; i < n; i++)
        {
            Object obj = list.get( (int) (n * Math.random()));
        }
        return (System.currentTimeMillis() - start);
    }

    public static void addRemovePerformance()
    {
        System.out.println("N\tArray\tLinked\tVector");
        for (int n = 1000; n <= 32000; n *= 2)
        {
            System.out.print(n + "\t" + addRemove(new ArrayList(), n));
            System.out.print("\t" + addRemove(new LinkedList(), n));
            System.out.println("\t" + addRemove(new Vector(), n));
        }
    }

    public static void accessPerformance()
    {
        System.out.println("N\tArray\tLinked\tVector");
        for (int n = 1000; n <= 32000; n *= 2)
        {
            ArrayList arrayList = new ArrayList();
            LinkedList linkedList = new LinkedList();
            Vector vector = new Vector();
            for (int i = 0; i < n; i++)
            {
                arrayList.add(new Double(i));
                linkedList.add(new Double(i));
                vector.add(new Double(i));
            }
            System.out.print(n + "\t" + jumpAround(arrayList, n));
            System.out.print("\t" + jumpAround(linkedList, n));
            System.out.println("\t" + jumpAround(vector, n));
        }
    }

    public static void main(String args[])
    {
        System.out.println("插入/删除时间");
        addRemovePerformance();
        System.out.println("随机访问时间");
        accessPerformance();
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?