4

When I using java there are something like double bracket initialization that actually make some runtime trade off. In scala I discover the simple way to initiate object property like

val button1: Button = new Button
button1.setText("START")
button1.setPrefWidth(100)

Which can be rewriten to

val button2: Button = new Button {
setText("PAUSE")
setPrefWidth(100)
}

Is these make any difference from performance or something else?

Mohammad Fajar
  • 957
  • 1
  • 12
  • 24

1 Answers1

4

The difference is that in the first case you instantiate a new Button object and set its properties to some values (text = "START" and width = 100) and in the second case you create an anonymous class that inherits from Button and initialize its properties in its anonymous initializer (or constructor, not sure - Java's anonymous classes cannot have constructors).

The second case can be roughly rewritten like this (if it weren't an anonymous class):

class MyButton extends Button {
  //constructor
  setText("START")
  setPrefWidth(100)
}

And when you call new MyButton you get an instance of MyButton with text set as "START" and prefWidth set as 100.

If you come from Java background consider this analogy:

Button button = new Button() {
    //anonymous initializer
    {
        setText("START");
        setPrefWidth(100);
    }
};
serejja
  • 22,901
  • 6
  • 64
  • 72
  • 1
    I recently read this post: http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization so, is there any performance impact with that initialization in scala? – Mohammad Fajar Mar 18 '14 at 18:14
  • I mean, is scala implementation of anonymous class differ from java? – Mohammad Fajar Mar 18 '14 at 18:16
  • I have actually no idea about the performance of this. I think I'll try to measure it soon – serejja Mar 18 '14 at 18:30
  • 3
    Ok, just tested. Initialization of 1000 `Button()` objects took approximately ~78 ms on my laptop. 1000 `Button{}` objects took approximately ~397 ms. 10 measurements for each case. So yes, there is a performance impact but it's not that critical to reject this type of initialization – serejja Mar 18 '14 at 19:01