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> generateWithElement() {
return <Foo>[
for (int i = 0; i < 1000; i++)
Foo(x: i, y: i + 1)
];
}
List<Foo> generateWithFilled() {
return List<Foo>.generate(1000, fill);
}
List<Foo> preallocate() {
var result = List<Foo>(1000);
for (int i = 0; i < 1000; i++)
result[i] = Foo(x: i, y: i + 1);
return result;
}
List<Foo> listAdd() {
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();
sw.start();
List<Foo> result;
for (var i = 0; i < 100; i++) {
result = generateWithElement();
}
sw.stop();
print(result.last);
print('for element took ${sw.elapsedMicroseconds}');
sw.reset();
sw.start();
for (var i = 0; i < 100; i++) {
result = generateWithFilled();
}
sw.stop();
print(result.last);
print('List.generate took ${sw.elapsedMicroseconds}');
sw.reset();
sw.start();
for (var i = 0; i < 100; i++) {
result = preallocate();
}
sw.stop();
print(result.last);
print('preallocate took ${sw.elapsedMicroseconds}');
sw.reset();
sw.start();
for (var i = 0; i < 100; i++) {
result = listAdd();
}
sw.stop();
print(result.last);
print('List.add took ${sw.elapsedMicroseconds}');
}
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.