使用 dart2js 编译为 JavaScript 时,使用构造函数创建的类实例是否const
比普通实例(使用构造函数创建)更优化?new
问问题
104 次
1 回答
2
这是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());
}
这就是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
。
于 2014-07-16T03:41:51.933 回答