Created
November 7, 2024 14:20
-
-
Save lukas-h/f91c2093587a9a444dc8474135ce38a7 to your computer and use it in GitHub Desktop.
Future.wait vs individual await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ignore_for_file: unused_local_variable | |
Future<void> main() async { | |
final start = DateTime.now(); | |
final firstFuture = Future<int>.delayed(const Duration(seconds: 1), () => 1); | |
final secondFuture = Future<double>.delayed(const Duration(seconds: 1), () => 1.0); | |
final thirdFuture = Future<String>.delayed(const Duration(seconds: 1), () => '1'); | |
// static types are given | |
final first = await firstFuture; | |
final second = await secondFuture; | |
final third = await thirdFuture; | |
final end = DateTime.now(); | |
// takes 1s | |
print('difference: ${end.difference(start).inSeconds}s'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ignore_for_file: unused_local_variable | |
Future<void> main() async { | |
final start = DateTime.now(); | |
final futures = await Future.wait([ | |
Future<int>.delayed(const Duration(seconds: 1), () => 1), | |
Future<double>.delayed(const Duration(seconds: 1), () => 1.0), | |
Future<String>.delayed(const Duration(seconds: 1), () => '1'), | |
]); | |
// static analysis doesn't give us an error if indexes are wrong, types are lost in list | |
final first = futures[0] as int; | |
final second = futures[1] as double; | |
final third = futures[2] as String; | |
final end = DateTime.now(); | |
// takes 1s | |
print('difference: ${end.difference(start).inSeconds}s'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment