Skip to content Skip to sidebar Skip to footer

Does Dart2js Optimize Const Objects Better?

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?

Solution 1:

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.

Post a Comment for "Does Dart2js Optimize Const Objects Better?"