I wrote a memory leak code.
import 'package:flutter/material.dart';
void main() {
runApp(MainApp());
}
class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: TextMemoryLeak(),
);
}
}
class TextMemoryLeak extends StatefulWidget {
@override
_TextMemoryLeakState createState() => _TextMemoryLeakState();
}
class _TextMemoryLeakState extends State<TextMemoryLeak> {
List memoryList = [];
@override
Widget build(BuildContext context) {
Scaffold scaffold = Scaffold(
appBar: AppBar(
title: Text('test memory leaks'),
),
body: Center(
child: Text('${memoryList.length + 1}'),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.map),
onPressed: () {
setState(() {
});
},
),
);
for (var i = 0; i < 100; ++i) {
memoryList.add(scaffold); // A memory leak has occurred
memoryList.add('A' * 1000);
}
return scaffold;
}
}
This is a very simple code.
Every time you click on the floatingButton
, it will be continuously added to the memoryList
without being removed. This is an obvious memory leak.
I once read an article about Flutter checking for memory leaks.
The principle is that the larger the memory size requested by a function, the greater the possibility of a memory leak. (I forgot where I saw it. If anyone knows, please tell me the address of this article.)
I don’t like this method because the memory requested by a function is very small, but it is a memory leak and it is difficult to check.
Another way is to use weakly referenced.
The principle is this.
var memoryList = [];
memoryList.add('111111');
var weakMap = new WeakMap()
weakMap.set(memoryList, true);
forceGC();
// According to the principle, after executing gc,
// if the memoryList key does not exist in the
// `WeakMap`,
// it means that the memoryList has recovered memory normally.
This troubleshooting method is very enjoyable. When I create an object, I make a weak reference to it to store it. When I destroy and force the use of GC, we can check the memory leaked objects through WeakMap
.
There are several issues:
Dart does not have a weak reference. May I ask if there is a launch plan?
Does dart have a similar method to know if the object has been properly recycled?
In addition to the above two methods, is there a better way for Flutter to check for memory leaks?
I used to develop a game in which a colleague wrote a piece of code with a memory leak and then left. It was too painful when I investigated later.
@munificent
Wow, I can see you here. I’m a game developer and I’ve seen the game design patterns you write and it’s great.