简体   繁体   中英

Does dart2js optimize const objects better?

使用dart2js编译为JavaScript时,使用const构造函数创建的类实例是否比使用普通实例(使用new构造函数创建)更优化?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM