Java匿名类效率的含义 [英] Java anonymous class efficiency implications

查看:105
本文介绍了Java匿名类效率的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种做法之间的效率(例如执行时间,代码大小等)是否存在差异?

Is there any difference in efficiency (e.g. execution time, code size, etc.) between these two ways of doing things?

以下是设计对象的人为例子并且什么都不做,但我的实际场景可能是创建新的线程,监听器等。假设以下代码片段在循环中发生,这样它可能会产生影响。

Below are contrived examples that create objects and do nothing, but my actual scenarios may be creating new Threads, Listeners, etc. Assume the following pieces of code happen in a loop so that it might make a difference.

使用匿名对象:

void doSomething() {
    for (/* Assume some loop */) {
        final Object obj1, obj2; // some free variables

        IWorker anonymousWorker = new IWorker() {
            doWork() {
                // do things that refer to obj1 and obj2
            }
        };
    }
}

首先定义一个班级:

void doSomething() {
    for (/* Assume some loop */) {
        Object obj1, obj2;
        IWorker worker = new Worker(obj1, obj2);
    }
}

static class Worker implements IWorker {
    private Object obj1, obj2;
    public CustomObject(Object obj1, Object obj2) {/* blah blah */}

    @Override
    public void doWork() {}
};


推荐答案

实际差异匿名类和顶级类之间的关系是匿名类将包含对外部类的隐式引用。

The only practical difference between the anonymous classes and the top-level classes is that the anonymous classes will hold an implicit reference to the outer class.

这不会在性能上表现出来,但是如果您将这些类序列化,则会对您产生影响。

This won't manifest itself in performance, but will impact you if you ever serialise these classes.

这篇关于Java匿名类效率的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆