【问题标题】:Does dart2js optimize const objects better?dart2js 是否更好地优化了 const 对象?
【发布时间】:2014-09-06 10:52:26
【问题描述】:

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

【问题讨论】:

    标签: javascript dart dart2js


    【解决方案1】:

    这里有 2 个元组实现:

    使用常量构造函数:

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

    使用新的构造函数:

    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

    这就是new Tuple 在输出中的样子:

    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); 并像这样使用:

    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-team)应该解决的问题。 const 对象应始终至少与非 const 对象一样好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多