0

Are there any memory or speed issues with creating many anonymous inner classes? In the following code, I like the succinctness of experiment1, but I am concerned that including anonymous class creation in a highly iterated loop would make it lose out to experiment2 for some dimension(s) of performance.

public class Test {
    interface Task {
        public void do();
    }

    public void experiment1 {
        for (int i = 0; i < 1000000; i++) {
            Task inner = new Task() {public void do() {/* stuff */}}
        }
    }

    public void experiment2 {
        class InnerClass implements Task {
            public void do() {/* stuff */}
        }
        for (int i = 0; i < 1000000; i++) {
            Task inner = new InnerClass();
        }
    }
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Brian Risk
  • 1,244
  • 13
  • 23
  • Have you tried timing it? – Joseph Young Dec 21 '15 at 15:33
  • 2
    If you compile that and inspect the bytecode, I expect you'll find that they are identical. In either case you have one .class file (for `Test$1` or `Test$InnerClass`). Within the loop you create an instance of the class. – dsh Dec 21 '15 at 15:37
  • 1
    You should prefer the succinctness of lambda expressions. Anonymous classes are no longer succinct. – Klitos Kyriacou Dec 21 '15 at 15:37

0 Answers0