|
// Adding this line so we can perform the variable assignment: num eachElement = 0; |
|
// ignore_for_file: unused_local_variable |
|
|
|
import 'dart:collection'; |
|
import 'dart:math'; |
|
|
|
void main(List<String> args) { |
|
final list = UnmodifiableListView( |
|
List<int>.generate(200000000, (index) => index), |
|
); |
|
|
|
final results = { |
|
'While-Loop Uncached Length': |
|
benchmarck(() => whileLoopUncachedLength(list)), |
|
'While-Loop Cached Length': benchmarck(() => whileLoopCachedLength(list)), |
|
'While-Loop Reversed': benchmarck(() => whileLoopReversed(list)), |
|
'For-Loop Uncached Length': benchmarck(() => forLoopUncachedLength(list)), |
|
'For-Loop Cached Length': benchmarck(() => forLoopCachedLength(list)), |
|
'For Loop Reversed': benchmarck(() => forLoopReversed(list)), |
|
'For-In Loop': benchmarck(() => forInLoop(list)), |
|
'For-Each Loop': benchmarck(() => forEachLoop(list)), |
|
}; |
|
|
|
final elements = results.entries.toList() |
|
..sort((a, b) => a.value > b.value ? -1 : 1); |
|
print('ms\tLoop'); |
|
for (var entry in elements) { |
|
print('${entry.value}\t${entry.key}'); |
|
} |
|
} |
|
|
|
int benchmarck(void Function() function) { |
|
final stopwatch = Stopwatch()..start(); |
|
function(); |
|
stopwatch.stop(); |
|
return stopwatch.elapsedMilliseconds; |
|
} |
|
|
|
void whileLoopUncachedLength(List<int> list) { |
|
var count = 0; |
|
num eachElement = 0; |
|
while (count < list.length) { |
|
eachElement = pow(list[count], 3); |
|
count++; |
|
} |
|
} |
|
|
|
void whileLoopCachedLength(List<int> list) { |
|
var count = 0; |
|
num eachElement = 0; |
|
final length = list.length; |
|
while (count < length) { |
|
eachElement = pow(list[count], 3); |
|
count++; |
|
} |
|
} |
|
|
|
void whileLoopReversed(List<int> list) { |
|
var count = list.length - 1; |
|
num eachElement = 0; |
|
while (count >= 0) { |
|
eachElement = pow(list[count], 3); |
|
count--; |
|
} |
|
} |
|
|
|
void forLoopUncachedLength(List<int> list) { |
|
num eachElement = 0; |
|
for (var i = 0; i < list.length; i++) { |
|
eachElement = pow(list[i], 3); |
|
} |
|
} |
|
|
|
void forLoopCachedLength(List<int> list) { |
|
num eachElement = 0; |
|
var length = list.length; |
|
for (var i = 0; i < length; i++) { |
|
eachElement = pow(list[i], 3); |
|
} |
|
} |
|
|
|
void forLoopReversed(List<int> list) { |
|
num eachElement = 0; |
|
for (var i = list.length - 1; i >= 0; i--) { |
|
eachElement = pow(list[i], 3); |
|
} |
|
} |
|
|
|
void forInLoop(List<int> list) { |
|
num eachElement = 0; |
|
|
|
for (var element in list) { |
|
eachElement = pow(element, 3); |
|
} |
|
} |
|
|
|
void forEachLoop(List<int> list) { |
|
num eachElement = 0; |
|
void fn(int element) => eachElement = pow(element, 3); |
|
list.forEach(fn); |
|
} |