为什么初始化ArrayList这么慢?

时间:2019-07-29 06:31:14

标签: java performance arraylist

我正在尝试以ArrayList的形式初始化边缘列表。我正在尝试使初始化花费不到700毫秒的时间。

我已经尝试过使用TreeSet和PriorityQueue,但是那些事情的速度明显慢了很多。 即使这样,ArrayList仍然要慢得多。

int n = 2000;
int m = 2000;
int[] N = new int[2002];
int[] M = new int[2002];
long start = System.currentTimeMillis();
ArrayList<Edge> E = new ArrayList();
for (int r = 0; r < m + 1; r++) {
    for (int c = 0; c < n + 1; c++) {
        if (r != m) {
            E.add(new Edge( r * (n + 1) + c, 
                            (r + 1) * (n + 1) + c, 
                            N[c + 1] - N[c]));
            }

        if (c != n) {
                E.add(new Edge(r * (n + 1) + c, 
                               r * (n + 1) + c + 1, 
                               M[r + 1] - M[r]));
        }
    }
}
long end = System.currentTimeMillis();
System.out.println(start - end);

class Edge implements Comparable<Edge> {
    public int from;
    public int to;
    public int weight;

    public Edge(int f, int t, int w ) {
        from = f;
        to = t;
        weight = w;
    }

    public int compareTo(Edge other) {
        if (this.weight == other.weight) {
            if (this.from == other.from) {
                return this.to - other.to;
            }
            return this.from - other.from;
        }
        return this.weight - other.weight;
    }
}

当仅测试相同大小的基本嵌套for循环时,(开始-结束)最终大约需要10毫秒。但是,当我测试此特定代码时,(开始-结束)最终大约是3000毫秒。谁能解释原因以及解决方法?

0 个答案:

没有答案