245 字
1 分钟
Dart Function.apply()
使用
例如存在如下函数:
int sum(int a, int b, {List<int>? more}) {
return a + b + (more?.reduce((value, element) => value + element) ?? 0);
}
可以直接通过:
sum(1, 2, more: [3, 4, 5]);
也可以通过:
Function.apply(sum, [1, 2], {#more: [3, 4, 5]});
性能差距
测试代码:
int sum(int a, int b, {List<int>? more}) {
return a + b + (more?.reduce((value, element) => value + element) ?? 0);
}
void bench(int times, Function() func) {
final sw = Stopwatch();
sw.start();
for (var i = 0; i < times; i++) {
func();
}
sw.stop();
print('Time: ${sw.elapsedMilliseconds}ms');
}
void main() {
const times = 1000000;
bench(times, () {
sum(1, 2, more: [3, 4, 5]);
});
bench(
times,
() => Function.apply(sum, [
1,
2
], {
#more: [3, 4, 5]
}));
}
使用如下代码编译:
dart compile exe test.dart
测试结果:
➜ test ./test.exe
Time: 24ms
Time: 959ms
为了防止编译器潜在的优化,我们可以使用如下代码:
void main() {
const times = 1000000;
var a = 1;
var b = 2;
var more = [3, 4, 5];
bench(times, () {
sum(a, b, more: more);
});
bench(
times,
() => Function.apply(sum, [
a,
b
], {
#more: more
}));
}
此时结果:
➜ test ./test.exe
Time: 40ms
Time: 930ms
Dart Function.apply()
https://blog.lpkt.cn/posts/dart-func-apply/