本文介绍了dart2js更好地优化const对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 const 构造函数创建的类实例比正常实例(使用 new 构造函数创建)更优化,

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?

推荐答案

这里是2个元组实现:

使用常量构造函数:

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());
}

这是 new Tuple 查看输出:

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 只创建一次 C.Tuple_10_20 = new S.Tuple(10,20); 并使用像这样:

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);
}

注意,在 new Tuple 函数调用已被其返回值文字替换,但它并没有发生在 const Tuple 输出。

这篇关于dart2js更好地优化const对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 23:21