Pacerier
Pacerier

Reputation: 89743

Does the compiler optimizes anonymous classes which do not add / override methods?

I was wondering if the compiler (ECJ, javac, or you can name your favourite compiler) optimizes anonymous classes which do not add or override methods of it's base class.

For example, for code that looks like this:

Snippet A:

Human h = new Human("John", 30);
h.setX(12.5);
h.setY(15.3);
//..
Eat(h);

I'd always prefer the syntax:

Snippet B:

Eat(new Human("John", 30){
    {
        setX(12.5);
        setY(15.3);
        //..
    }
});

However I understand that unlike the WITH keyword we have in vb.net, this is not just syntax sugar. What we are telling the compiler to do is to create an anonymous subclass of Human whose constructor consists of the code within the bracers (which is also why we can't use this syntax-sugar for final classes).

The problem now is that I use this syntax-sugar all the time (like for example overriding onclick in UI listeners etc), it's like one of my coding style/habits.

Hence the question:

  1. Does the compiler optimizes this kind of syntax? (i.e. it realised that no anonymous classes needs to be generated, and the performance of Snippet B would be the same as Snippet A)

  2. If the answer to (1) is "no", I was wondering is it (the more-than-expected abundance of anonymous classes due to this coding style) a noticeable impact such that it is highly recommended that for future projects (coding applications for the average mobile device) we should always adhere to the style in Snippet A ?

Upvotes: 1

Views: 124

Answers (2)

Matthew Farwell
Matthew Farwell

Reputation: 61705

Yes, it will (always) generate an anonymous class (called Human$1). You can see this by examining the class files that are output. You should have a Human.class and Human$1.class as output.

As for performance implications, there will be two classes (bigger, more work for the VM), references from one to the other (because the anonymous inner class will have a link to the outer class). This may have a effect on performance, I suppose, but only minor. You'd have to test it.

However, it's not particularly idiomatic java to do it this way. The idiomatic way would be to have another constructor.

Upvotes: 1

John Vint
John Vint

Reputation: 40256

The compiler will create a separate binary class.

For instance if you have

class Foo{

}

class Bar{
  Foo otherFoo = new Foo(){

  }
}

In your bin/target directory you will have three classes

  • Bar.class
  • Bar$1.class
  • Foo.class

Here the anonymous subclass is Bar$1.class

Upvotes: 1

Related Questions