Skip to content

Instantly share code, notes, and snippets.

@jonahwilliams
Last active June 11, 2020 01:25
Show Gist options
  • Save jonahwilliams/e8936a2370a539bf50bd321b5d74eaad to your computer and use it in GitHub Desktop.
Save jonahwilliams/e8936a2370a539bf50bd321b5d74eaad to your computer and use it in GitHub Desktop.
List allocation benchmark
// 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.
import 'package:flutter/widgets.dart';
List<int> generateWithElement() {
return <int>[
for (int i = 0; i < 1000; i++)
i
];
}
List<int> generateWithFilled() {
return List<int>.generate(1000, fill);
}
List<int> preallocate() {
var result = List<int>(1000);
for (int i = 0; i < 1000; i++)
result[i] = i;
return result;
}
List<int> listAdd() {
var result = <int>[];
for (int i = 0; i < 1000; i++)
result.add(i);
return result;
}
int fill(int value) {
return value;
}
void main() {
var sw = Stopwatch();
sw.start();
List<int> 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}');
}
@jonahwilliams
Copy link
Author

The best way to run this is to comment out all but 1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment