1

Are class instances created with a const constructor more optimized than the normal instances (created with a new constructor) when compiled to JavaScript with dart2js?

hopper
  • 13,060
  • 7
  • 49
  • 53
JAre
  • 4,666
  • 3
  • 27
  • 45

1 Answers1

2

Here is 2 tuple implementations:

With a constant constructor:

class Tuple{
  final _1, _2;
  foo()=> _1 + _2;
  const Tuple(this._1,this._2);
}

void main() {
  var a = const Tuple(10,20);
  var b = const Tuple(10,20);
  print(a);
  print(b);
  print(a.foo());
}

With a new constructor:

class Tuple{
  final _1, _2;
  foo()=> _1 + _2;
  Tuple(this._1,this._2);
}
void main() {
  var a = new Tuple(10,20);
  var b = new Tuple(10,20);
  print(a);
  print(b);
  print(a.foo());
}

dart2js outputs comparison

That is how new Tuple looks in the output:

main: function() {
    P.print(new S.Tuple(10, 20));
    P.print(new S.Tuple(10, 20));
    P.print(30);
}

const Tuple is created only once C.Tuple_10_20 = new S.Tuple(10, 20); and used like this:

main: function() {
    P.print(C.Tuple_10_20);
    P.print(C.Tuple_10_20);
    P.print(C.Tuple_10_20._1 + C.Tuple_10_20._2);
}

Note that in the case of new Tuple the function call has been replaced with its return value literal but it didn't happen for the const Tuple output.

JAre
  • 4,666
  • 3
  • 27
  • 45
  • Please include the relevant part of the diff in your answer; your link is set to expire in one year. – Ry- Jul 16 '14 at 03:44
  • 3
    That's something we (dart2js-team) should fix. Const-objects should always be at least as good as non-const objects. – Florian Loitsch Jul 16 '14 at 05:42