testlistperformance.java

来自「JAVA 经典代码」· Java 代码 · 共 76 行

JAVA
76
字号
import java.util.*;

public class TestListPerformance {
  private static int REPTEXEC = 10000;
  private static int QUANTITY = 100;
  public static void main(String[] args) {
    System.out.println(REPTEXEC + " repetitions");

    List tempList = new ArrayList();
    testList(tempList);
    tempList = null;
    System.gc(); //强制垃圾回收

    tempList = new LinkedList();
    testList(tempList);
    tempList = null;
    System.gc(); //强制垃圾回收

    tempList = new Vector();
    testList(tempList);
    tempList = null;
    System.gc(); //强制垃圾回收
  } // main方法结束

  public static void fill(Collection c, int count) {
    for(int i = 0; i < count; i++)
      c.add(Integer.toString(i));
  } // fill方法结束

  public static void testList(List a) {
    System.out.println("_____________________________________");
    System.out.println("测试" + a.getClass().getName().replaceAll("\\w+\\.", ""));
    fill(a, QUANTITY);

    //测试取操作
    long start = System.currentTimeMillis();
    for (int i = 0; i < REPTEXEC; i++) {
      for (int j = 0; j < QUANTITY; j++)
        a.get(j);
    }
    long end = System.currentTimeMillis();
    System.out.println("取操作用时: " + (end - start));

    //测试迭代操作
    start = System.currentTimeMillis();
    for (int i = 0; i < REPTEXEC; i++) {
      Iterator it = a.iterator();
      while (it.hasNext())
        it.next();
    }
    end = System.currentTimeMillis();
    System.out.println("迭代操作用时: " + (end - start));

    //测试增加操作
    int half = a.size() / 2;
    String s = "test";
    start = System.currentTimeMillis();
    ListIterator listit = a.listIterator(half);
    for (int j = 0; j < REPTEXEC * 10; j++)
      listit.add(s);
    end = System.currentTimeMillis();
    System.out.println("增加操作用时: " + (end - start));

    //测试删除操作
    half = a.size() / 2;
    s = "test";
    listit = a.listIterator(half);
    while(listit.hasNext()) {
      listit.next();
      listit.remove();
    }
    end = System.currentTimeMillis();
    System.out.println("删除操作用时: " + (end - start));
  } // testList方法结束
} // 类TestPerformance结束

⌨️ 快捷键说明

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