Closed
Description
Scenario
Sometimes we design an API to allow the returned value to be a Future or a Sync, which depends on its logic, so we will declare the returned value to be a Future in the function/method syntax.
For example,
foo() async {
if (...) return 1; //sync value;
else return new Future.value(2); // a future value
}
And then if the 'foo()' is called in a for loop for thousand� times, the async and await syntax will be the performance nightmare.
For example,
import 'dart:async';
main () async {
// Async syntax
var sw1 = new Stopwatch()..start();
var count1 = 0;
for (var i = 0; i < 10000; i++) {
count1 += await foo();
}
print('Async and Await: ${sw1.elapsedMilliseconds}ms');
// Future syntax
var sw2 = new Stopwatch()..start();
var count2 = 0;
for (var i = 0; i < 10000; i++) {
bar().then((_) {
count2 += _;
if (i == 9999)
print('Future: ${sw2.elapsedMilliseconds}ms');
});
}
// Sync syntax
var sw3 = new Stopwatch()..start();
var count3 = 0;
for (var i = 0; i < 10000; i++) {
count3 += baz();
}
print('Sync: ${sw3.elapsedMilliseconds}ms');
}
foo() async {
return 1;
}
Future<int> bar() {
return new Future.value(2);
}
baz() {
return 3;
}
The result will be
Async and Await: 130ms
Sync: 0ms
Future: 79ms
An Idea
In our workaround, we implement a Sync class to extend the Future class, and by using the syntax of bar() to cheat the compiler, and it can speed up in the runtime.
For example,
Future<int> bar() {
if (isSync) return new Sync.value(2);
else return new Future.value(2);
}
So it could be an idea to make this trick in Dart VM.