Java anonymous class efficiency implications
- by Po
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.
Using anonymous objects:
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
}
};
}
}
Defining a class first:
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() {}
};
Thank you :)