Skip to content

Instantly share code, notes, and snippets.

@olumidayy
Created October 16, 2021 18:59
Show Gist options
  • Save olumidayy/2be93c26142c3021fca7b627f23106ae to your computer and use it in GitHub Desktop.
Save olumidayy/2be93c26142c3021fca7b627f23106ae to your computer and use it in GitHub Desktop.
Future.wait() vs Future.forEach()
void main() async {
Stopwatch stopwatch = Stopwatch()..start();
List<int> nums = [1, 2, 3, 4, 5];
print(await usingForeach(nums));
print('usingForeach() executed in ${stopwatch.elapsed}');
// Reeset timer
stopwatch.reset();
print(await usingWait(nums));
print('usingWait() executed in ${stopwatch.elapsed}');
}
Future<int> squareMyNumber(int number) async {
// You can edit duration here
await Future.delayed(Duration(seconds: 3));
return number * number;
}
Future<List<int>> usingForeach(List<int> nums) async {
List<int> squares = [];
await Future.forEach(nums, (int no) async {
int square = await squareMyNumber(no);
squares.add(square);
// print(square);
});
return squares;
}
Future<List<int>> usingWait(List<int> nums) async {
List<int> squares;
squares = await Future.wait(nums.map((int no) => squareMyNumber(no)));
return squares;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment