有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

访问者模式如何解释这两个Java程序运行时间的差异?

我有两段简单的Java代码。两者实现相同的功能

第一个版本使用访问者模式,而第二个版本重新定位代码以删除双重分派。我认为第二版应该运行得更快。但是,在几次跑步中,第一次跑得更快10%。这怎么解释呢?这难道不是衡量这一点的正确方法吗

角落案例没有得到很好的处理(这里不需要担心),并且append故意没有在固定时间内完成(我想最大限度地增加双重分派的数量)

样本1(访客):

interface List {
    public void accept(Visitor v);
}

interface Visitor {
    public void visit(Nil x);
    public void visit(Cons x);
}

class Nil implements List {
    public void accept(Visitor v) {
        v.visit(this);
    }
}

class Cons implements List {
    public int head;
    public List tail;
    public Cons(int d, List l) {
        this.head = d;
        this.tail = l;
    }

    public void accept(Visitor v) {
        v.visit(this);
    }
}

class Append implements Visitor {
    Cons prev;
    int data;
    public Append (int d) {
        this.data = d;
    }

    public void visit(Nil x) {
        Cons n = new Cons(this.data, x);
        prev.tail = n;
    }

    public void visit(Cons x) {
        this.prev = x;
        x.tail.accept(this);
    }
}

public class ListVisBenchmark {
    public static void main(String[] args) throws Exception {
        int TEST_SIZE = 20000;
        Cons l;

        long t1 = System.nanoTime();
        for (int i = 0; i < 5; i++) {
            l = new Cons(0, new Nil());
            for (int j = 0; j < TEST_SIZE; j++) {
                l.accept(new Append(j));
            }
        }
        long t2 = System.nanoTime();
        System.out.println("Exec : " + ((t2-t1)*1e-6) + " ms");
    }
}

样本2(备选):

interface List {
    public void __Append__(Append v);
}

interface Visitor {
}

class Nil implements List {
    public void __Append__(Append v) {
        Cons n = new Cons(v.data, this);
        v.prev.tail = n;
    }
}

class Cons implements List {
    public int head;
    public List tail;
    public Cons(int d, List l) {
        this.head = d;
        this.tail = l;
    }

    public void __Append__(Append v) {
        v.prev = this;
        this.tail.__Append__(v);
    }
}

class Append implements Visitor{
    Cons prev;
    int data;
    public Append (int d) {
        this.data = d;
    }
}

public class ListOptBenchmark {
    public static void main(String[] args) throws Exception {
        int TEST_SIZE = 20000;
        Cons l;

        long t1 = System.nanoTime();
        for (int i = 0; i < 5; i++) {
            l = new Cons(0, new Nil());
            for (int j = 0; j < TEST_SIZE; j++) {
                l.__Append__(new Append(j));
            }
        }
        long t2 = System.nanoTime();

        System.out.println("Exec : " + ((t2-t1)*1e-6) + " ms");

    }
}

每个程序的输出:

$ java ListVisBenchmark
Exec : 7500.791179 ms

$ java ListOptBenchmark
Exec : 8183.261969 ms

多次运行得到几乎相似的结果。始终,Vis<;选择


共 (0) 个答案