-
Notifications
You must be signed in to change notification settings - Fork 1.7k

Description
Running this program in dartpad:
import "dart:async";
main() async {
var sw = Stopwatch()..start();
int N = 10;
int result = await (int n) async {
for (int i = 0; i < n; i++) {
await Future.value(1);
}
return n;
}(N);
print(result);
print("t=${sw.elapsedMicroseconds}");
sw.reset();
result = await (int n) async {
for (int i = 0; i < n; i++) {
await Future(() => 1);
}
return n;
}(N);
print(result);
print("t=${sw.elapsedMicroseconds}");
return result;
}
Results:
10
t=5201
10
t=5814799
The culprit is Timer.run() method used inside Future constructor.
The same program, when run on VM, produces the following output (with N=100000)
100000
t=64293
100000
t=496046
Exited
Still slower, but only by 7-8 times, not 1000 times. (I expected it to be slower by 2 times max)
(I also compared the Future.value() version in dartpad vs Future.value() in VM. In javascript, it's slower by 2.5 times, which is reasonable).
This affects all methods that use Timer.run()
under the hood: Future.delayed
, Future.microtask
, scheduleMicrotask
and probably more.
Flutter also uses Timer.run
directly in some places. Maybe this issue should be open against Timer.run
instead - not sure.
EDIT: when I run the same test in MS Edge, the timing, in absolute terms, is much better, but the ratio is still around 500.
When you try to reproduce, set N to a higher value (say, 1000 or 10000).