我正在尝试模拟内存泄漏Streams
(出于教育目的),但如果 GC 尚未运行,我无法确定内存是否真的泄漏。
我可以在纯 Dart 测试中强制执行 GC 扫描吗?
您可以通过 Dart DevTools Web GUI 来完成此操作。https://dart.dev/tools/dart-devtools https://dart.dev/tools/dart-devtools
更新了使用 vm_service 包的示例
对于较新的 Dart 版本,我们可以使用dart:developer
用于与 Dart VM 通信的 API。新版也是这样Dart 开发工具 https://dart.dev/tools/dart-devtools从虚拟机获取数据并进行诸如触发垃圾收集器之类的操作,您仍然可以通过进入 Web 界面手动执行这些操作。
如果您想从代码本身触发此操作,可以使用vm_service https://pub.dev/packages/vm_service包,可以轻松地与 Dart VM 服务协议中的 API 进行交互。
可以在这里看到一个例子:
import 'dart:developer';
import 'dart:isolate';
import 'package:vm_service/vm_service_io.dart';
Future<void> main(List<String> args) async {
final serverUri = (await Service.getInfo()).serverUri;
if (serverUri == null) {
print('Please run the application with the --observe parameter!');
return;
}
final isolateId = Service.getIsolateID(Isolate.current)!;
final vmService = await vmServiceConnectUri(_toWebSocket(serverUri));
final profile = await vmService.getAllocationProfile(isolateId, gc: true);
print(profile.memoryUsage?.heapUsage);
}
List<String> _cleanupPathSegments(Uri uri) {
final pathSegments = <String>[];
if (uri.pathSegments.isNotEmpty) {
pathSegments.addAll(uri.pathSegments.where(
(s) => s.isNotEmpty,
));
}
return pathSegments;
}
String _toWebSocket(Uri uri) {
final pathSegments = _cleanupPathSegments(uri);
pathSegments.add('ws');
return uri.replace(scheme: 'ws', pathSegments: pathSegments).toString();
}
The getAllocationProfile https://pub.dev/documentation/vm_service/latest/vm_service/VmService/getAllocationProfile.html方法采用可选参数gc
其记录为:
If gc
提供并设置为 true,则在收集分配信息之前将尝试进行垃圾收集。无法保证垃圾收集会实际执行。
所以这确实是你能做的最好的事情。此外,此解决方案仅在程序启动时才有效--observe
范围。因此,除了调试目的之外,不应将其用于其他目的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)