Skip to content

Instantly share code, notes, and snippets.

@icatalud
Last active October 6, 2019 19:53
Show Gist options
  • Save icatalud/dc28bd3bdd7c13b39c308b7abb9a9d8c to your computer and use it in GitHub Desktop.
Save icatalud/dc28bd3bdd7c13b39c308b7abb9a9d8c to your computer and use it in GitHub Desktop.
Set and Map add operation benchmark
import 'package:benchmark_harness/benchmark_harness.dart';
void main() {
print('Running app');
runMiscBenchmarks();
print('-----------------------------------------------------');
print('-------------END------------------------------------');
print('-----------------------------------------------------');
}
typedef SetCreator<T> = Set<T> Function();
typedef MapCreator<T> = Map<T, T> Function();
plainAddSet<T>(T obj, [int n = 1000]) {
var s = Set<T>();
for (var i = 0; i < n; i++) {
s.add(obj);
}
}
plainAddMap<T>(T obj, [int n = 1000]) {
var map = Map<T, T>();
for (var i = 0; i < n; i++) {
map[obj] = obj;
}
}
void runMiscBenchmarks() {
print('--- Set benchmark ---');
runAddingBenchmark<Set>(plainAddSet);
print('');
print('--- Map benchmark ---');
runAddingBenchmark<Map>(plainAddMap);
}
typedef ParameterFunc<V> = Function(V);
void Function() createPlainAdd<T>(Function(T) addManyTimes, T value) {
return () => addManyTimes(value);
}
void runAddingBenchmark<T>(ParameterFunc addManyTimes) {
final type = T.toString().split('<')[0];
benchmarkFunction(
createPlainAdd<int>(addManyTimes, 12345), 'Warm app int $type');
var objTime = benchmarkFunction(
createPlainAdd<Object>(addManyTimes, Object()), 'Add Object in $type');
var intTime =
benchmarkFunction(createPlainAdd<int>(addManyTimes, 12345), 'Int $type');
var stringTime = benchmarkFunction(
createPlainAdd<String>(addManyTimes, 'MyString'), 'String $type');
var dynTime = benchmarkFunction(
createPlainAdd(addManyTimes, Object()), 'Dynamic $type');
var objIntTime = benchmarkFunction(
createPlainAdd(addManyTimes, 12345), 'Object $type but value int');
print('\n$type summary:');
print('Object/int time ratio: ${objTime / intTime}');
print('Object/String time ratio: ${objTime / stringTime}');
print('Object/dynamic time ratio: ${objTime / dynTime}');
print('Object/int(Object typed) time ratio: ${objTime / objIntTime}');
}
double benchmarkFunction(f, [messagePrefix = 'Function']) {
var avgTime = BenchmarkBase.measureFor(f, 2000);
print('$messagePrefix average time: $avgTime us');
return avgTime;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment