Java 匿名类效率影响
2022-09-01 14:54:55
这两种做事方式在效率(例如执行时间,代码大小等)上是否有任何差异?
以下是创建对象而不执行任何操作的人为示例,但我的实际方案可能是创建新的线程,侦听器等。假设以下代码片段在循环中发生,以便它可能会有所作为。
使用匿名对象:
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() {}
};