Skip to content

Instantly share code, notes, and snippets.

@yjbanov
Created June 11, 2020 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yjbanov/7d8e2c2fa2971f7d421720c9409ff6b8 to your computer and use it in GitHub Desktop.
Save yjbanov/7d8e2c2fa2971f7d421720c9409ff6b8 to your computer and use it in GitHub Desktop.
// 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