Skip to content

Instantly share code, notes, and snippets.

@Abion47
Created December 14, 2019 01:33
Show Gist options
  • Save Abion47/bfb2243e475230a330587239946d2e3c to your computer and use it in GitHub Desktop.
Save Abion47/bfb2243e475230a330587239946d2e3c to your computer and use it in GitHub Desktop.
Loop and filter comparison
import 'dart:math';
// Generate a list of numbers with a configurable length
// The numbers range from 1 to 1 million
// The goal is to then generate a list of all numbers in that list
// which are less than 5 hundred thousand
// This script compares three approaches:
// typical for loop, iterator-based for loop, and generator-based where method
void main (){
int valuesLength = 1000000;
preloadValues(valuesLength);
withForLoop();
withForEachLoop();
withWhere();
}
final values = <int>[];
void preloadValues(int sampleSize) {
values.clear();
final r = Random();
for (int i = 0; i < sampleSize; i++) {
values.add(r.nextInt(1000000));
}
}
void withForLoop() {
final start = DateTime.now();
final results = <int>[];
for (int i = 0; i < values.length; i++) {
if (values[i] < 500000) {
results.add(i);
}
}
final end = DateTime.now();
print('withForLoop method duration: ${end.difference(start)}');
}
void withForEachLoop() {
final start = DateTime.now();
final results = <int>[];
for (int v in values) {
if (v < 500000) {
results.add(v);
}
}
final end = DateTime.now();
print('withForEachLoop method duration: ${end.difference(start)}');
}
void withWhere() {
final start = DateTime.now();
final results = values.where((i) => i < 500000).toList();
final end = DateTime.now();
print('withWhere method duration: ${end.difference(start)}');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment