Skip to content

Instantly share code, notes, and snippets.

@yjbanov

yjbanov/main.dart

Created Jun 11, 2020
Embed
What would you like to do?
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
class Foo {
Foo({this.x, this.y});
final int x;
final int y;
toString() => '($x, $y)';
}
List<Foo> runElement() {
return <Foo>[
for (int i = 0; i < 1000; i++)
Foo(x: i, y: i + 1)
];
}
List<Foo> runGenerateWithFilled() {
return List<Foo>.generate(1000, fill);
}
List<Foo> runPreallocate() {
var result = List<Foo>(1000);
for (int i = 0; i < 1000; i++)
result[i] = Foo(x: i, y: i + 1);
return result;
}
List<Foo> runAdd() {
var result = <Foo>[];
for (int i = 0; i < 1000; i++)
result.add(Foo(x: i, y: i + 1));
return result;
}
Foo fill(int value) {
return Foo(x: value, y: value + 1);
}
void main() {
var sw = Stopwatch();
final List<List<Foo>> results = <List<Foo>>[];
int element = 0;
int generateWithFilled = 0;
int preallocate = 0;
int add = 0;
for (int i = 0; i < 100; i++) {
List<Foo> result;
sw.reset();
sw.start();
result = runElement();
sw.stop();
element += sw.elapsedMicroseconds;
sw.reset();
sw.start();
result = runGenerateWithFilled();
sw.stop();
generateWithFilled += sw.elapsedMicroseconds;
sw.reset();
sw.start();
result = runPreallocate();
sw.stop();
preallocate += sw.elapsedMicroseconds;
sw.reset();
sw.start();
result = runAdd();
sw.stop();
add += sw.elapsedMicroseconds;
results.add(result);
}
print('for element took ${element}');
print('List.generate took ${generateWithFilled}');
print('preallocate took ${preallocate}');
print('List.add took ${add}');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.