<p>包装速度慢6.3倍的示例代码:</p>
<ol>
<li>仅构造函数wrapps值。如果您需要conversion,请使用其他方法,例如其他额外的构造函数。在</li>
<li>拆分比较运算符以减少不必要的类型检查。在</li>
<li>改进了算术运算符,增加了类型检查。在</li>
<li>Python类型组合成组$PyType。这样可以减少类型检查。在</li>
</ol>
<p>从该示例中删除了不必要的代码。在</p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:io';
fib(n) {
if (n <= 2) {
return 1;
} else {
return (fib((n - 1)) + fib((n - 2)));
}
}
fib2(n) {
if (n <= new $PyNum(2)) {
return new $PyNum(1);
} else {
return (fib2((n - new $PyNum(1))) + fib2((n - new $PyNum(2))));
}
}
main() {
measure("fib", () => stdout.writeln(fib(42)));
measure("fib2", () => stdout.writeln(fib2(new $PyNum(42))));
}
void measure(String msg, f()) {
var sw = new Stopwatch();
sw.start();
f();
sw.stop();
print("$msg: ${sw.elapsedMilliseconds}");
}
class $PyTypes {
static const $PyTypes NUM = const $PyTypes("NUM");
final String name;
const $PyTypes(this.name);
}
abstract class $PyType {
$PyTypes get pyType;
}
class $PyNum extends $PyType {
final int value;
$PyTypes get pyType => $PyTypes.NUM;
$PyNum(this.value);
operator +(other) {
if (other is $PyType) {
switch (other.pyType) {
case $PyTypes.NUM:
$PyNum pyNum = other;
return new $PyNum(value + pyNum.value);
}
} else if (other is int) {
return new $PyNum(value + other);
}
throw new ArgumentError("other: $other");
}
operator -(other) {
if (other is $PyType) {
switch (other.pyType) {
case $PyTypes.NUM:
$PyNum pyNum = other;
return new $PyNum(value - pyNum.value);
}
} else if (other is int) {
return new $PyNum(value - other);
}
throw new ArgumentError("other: $other");
}
operator ==(other) {
if (other is $PyType) {
switch (other.pyType) {
case $PyTypes.NUM:
$PyNum pyNum = other;
return value == pyNum.value;
}
} else if (other is int) {
return value == other;
}
throw new ArgumentError("other: $other");
}
operator <(other) {
if (other is $PyType) {
switch (other.pyType) {
case $PyTypes.NUM:
$PyNum pyNum = other;
return value < pyNum.value;
}
} else if (other is int) {
return value < other;
}
throw new ArgumentError("other: $other");
}
operator <=(other) {
if (other is $PyType) {
switch (other.pyType) {
case $PyTypes.NUM:
$PyNum pyNum = other;
return value <= pyNum.value;
}
} else if (other is int) {
return value <= other;
}
throw new ArgumentError("other: $other");
}
String toString() => value.toString();
}
</code></pre>