詳解flutter engine 那些沒被釋放的東西
由于flutter一直存在內(nèi)存泄漏的問題,導致很多開發(fā)者不勝困擾,博主在0.9.4就開始對其代碼內(nèi)部內(nèi)存問題在engine層面修改代碼,得到解決,但是對于每個版本都需要跟隨官方打包,對于開發(fā)者并不是很友好。
然而喜出望外的是,在后來的幾個版本中,官方內(nèi)置開發(fā)了手動釋放內(nèi)存的方式:smile_cat:
/** * Destroy running context for an engine. * * This method can be used to force the FlutterEngine object to release all resources. * After sending this message, the object will be in an unusable state until it is deallocated. * Accessing properties or sending messages to it will result in undefined behavior or runtime * errors. */ - (void)destroyContext;
翻譯如下:
銷毀引擎的運行上下文。 此方法可用于強制FlutterEngine對象釋放所有資源。 發(fā)送此消息后,對象將處于不可用狀態(tài),直到解除分配為止。 訪問屬性或向其發(fā)送消息將導致未定義的行為或運行時錯誤。
但是 , 但是 , 但是 ,(重要的事說三遍) 在Flutter engine開發(fā)群里面,有群友反饋還有很多問題
- 無法完全釋放內(nèi)存
- 偶現(xiàn)崩潰
偶現(xiàn)崩潰的是什么鬼,暫時沒有遇到,不好說。 之前博主遇到的崩潰是自己使用方式的問題,在fluttervc關閉之后還有任務在執(zhí)行methodchannel,即還在調(diào)用plugin,這個可以在開發(fā)上避免。 值得注意的是,flutter中使用c++實現(xiàn),自己對于內(nèi)存管理并不是很好
內(nèi)存問題自測如下

確實存在問題,還有將近30M沒有被釋放,查看一下當前內(nèi)存對象,如下圖

一個一個看還有那些沒有被釋放吧
android:LruCache
Least Recently Used 近期最少使用算法。 內(nèi)存管理的一種頁面置換算法,對于在內(nèi)存中但又不用的數(shù)據(jù)塊(內(nèi)存塊)叫做LRU,flutter engine 會根據(jù)哪些數(shù)據(jù)屬于LRU而將其移出內(nèi)存而騰出空間來加載另外的數(shù)據(jù)。
dart::BackgroundComplier 對isolate編譯優(yōu)化的類
BackgroundCompiler 在后臺線程中運行優(yōu)化編譯的類。 實現(xiàn):每個隔離一個任務,它與擁有isolate一起消失,后臺編譯器中沒有OSR編譯。
dart::bin::socket
vm和開發(fā)平臺通信的機制,比如jit即時編譯的dill文件,通過socket傳遞給dart vm,vm通過rpc加載文件,重置線程,從而實現(xiàn)hotreload熱重載
dart::BoolPrameter
- dart::EnumParameter
- dart::IdParameter
- dart::IdParameter
- dart::xxxPrameter
定義在dart vm,service.cc中,都繼承自MethodParameter,做對應參數(shù)校驗,參數(shù)解析用。編譯dart文件用的
dart::OSThread
在dart 運行時負責操作系統(tǒng)線程,創(chuàng)建線程,移除線程,線程查找與管理。 如下圖

FlutterEngineRegistrar 注冊使用key注冊plugin的地方,所有plugin調(diào)用dart底層的方法都會通過 handlemethodcall 回調(diào)給使用者, 其初始化的地方是引起內(nèi)存泄漏的地方
- (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(FlutterEngine*)flutterEngine {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_pluginKey = pluginKey;// [pluginKey retain];
_flutterEngine = flutterEngine;// [flutterEngine retain];
return self;
}
此處有一篇文章介紹,解決engine的循環(huán)引用文章
FlutterStandardMethodCodec 標準方法編解碼
FlutterStringCodec string編解碼 FlutterJsonMessageCodec json編解碼
不看不知道,一看嚇一跳,也竟然是個單例,當然不會被釋放了,也能理解,在flutter中用到jsonmssage的地方很多,用不著每次都初始化

代碼實現(xiàn)的地方
@implementation FlutterJSONMessageCodec
+ (instancetype)sharedInstance {
static id _sharedInstance = nil;
if (!_sharedInstance) {
_sharedInstance = [FlutterJSONMessageCodec new];
}
return _sharedInstance;
}
std:share_ptrxxx 共享指針
指針獲取 flutter isolate service dartvm symbolmapping

~~ 文章完 ~~
如果你想深入討論flutter的問題,歡迎加入我們的QQ群 217429001
完整測試代碼如下
#import "FlutterTesterViewController.h"
#import <Flutter/Flutter.h>
#import "GeneratedPluginRegistrant.h"
@interface FlutterTesterViewController ()
@property (nonatomic, weak) FlutterViewController * ctr;
@property (nonatomic, weak) FlutterEngine * engine;
@end
@implementation FlutterTesterViewController
- (void)viewDidLoad {
[super viewDidLoad];
float Y = 210;
[self createButton:@"加載boundle資源" frame:CGRectMake(80.0, Y, 160.0, 40.0) action:@selector(handleBoundleResource )];
Y += 40.0 + 10;
[self createButton:@"autorelease" frame:CGRectMake(80.0, Y, 160.0, 40.0) action:@selector(handleAutoRelase)];
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"flutter_assets"] ;
NSLog(@"path: %@",path);
}
-(void)handleNetWorkResource:(UIButton *)button{
}
/**
* 加載boundle資源
*/
- (void)handleBoundleResource {
FlutterDartProject * dart = [[FlutterDartProject alloc] init];
FlutterEngine * engine = [[FlutterEngine alloc] initWithName:@"ios.dart.flutter"
project:dart];
[engine runWithEntrypoint:nil];
FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
[GeneratedPluginRegistrant registerWithRegistry:flutterViewController];
[self addBackButton:flutterViewController];
[flutterViewController setInitialRoute:@"route1"];
[self presentViewController:flutterViewController animated:YES completion:nil];
self.engine = engine;
}
-(void)handleAutoRelase{
FlutterBasicMessageChannel* channel;
FlutterEngine * engine;
@autoreleasepool {
FlutterViewController* flutterViewController =
[[FlutterViewController alloc] init];
channel = flutterViewController.engine.systemChannel;
engine = flutterViewController.engine;
NSLog(@"engine111:%@",engine);
}
NSLog(@"engine222:%@",engine);
[channel sendMessage:@"Hello!"];
[channel setMessageHandler:^(id _Nullable message, FlutterReply _Nonnull callback) { }];
}
-(void)addBackButton:(UIViewController *)flutterViewController{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
[btn setTitle:@"關閉" forState:UIControlStateNormal];
btn.frame = CGRectMake(10, 100, 50, 30);
[btn addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside];
[flutterViewController.view addSubview:btn];
self.ctr = flutterViewController;
});
}
-(void)buttonTap:(id)sender{
// [self.navigationController popViewControllerAnimated:YES];
__weak __typeof(self)weakSelf = self;
[self.ctr dismissViewControllerAnimated:YES completion:^{
[weakSelf.engine destroyContext];
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(UIButton *)createButton:(NSString *)title frame:(CGRect)frame action:(SEL)selector{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
action:selector
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title forState:UIControlStateNormal];
UIColor * bgcolor = [UIColor colorWithRed:arc4random()%256/255. green:arc4random()%256/255. blue:arc4random()%256/255. alpha:1];
[button setBackgroundColor:bgcolor];
button.frame = frame;
[self.view addSubview:button];
return button;
}
@end
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
android RecyclerView實現(xiàn)條目Item拖拽排序與滑動刪除
本篇文章主要介紹了android RecyclerView實現(xiàn)條目Item拖拽排序與滑動刪除,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03
Android UI控件之ImageSwitcher實現(xiàn)圖片切換效果
這篇文章主要為大家詳細介紹了Android UI控件之ImageSwitcher實現(xiàn)圖片切換效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12
Android自定義ViewGroup實現(xiàn)可滾動的橫向布局(2)
這篇文章主要介紹了Android自定義ViewGroup實現(xiàn)可滾動的橫向布局,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12
ListView點擊Item展開菜單實現(xiàn)代碼詳解
這篇文章主要介紹了ListView點擊Item展開菜單實現(xiàn)代碼詳解的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-06-06
Android開發(fā)之TabHost選項卡及相關疑難解決方法
這篇文章主要介紹了Android開發(fā)之TabHost選項卡及相關疑難解決方法,結合實例形式較為詳細的分析了Android開發(fā)中TabHost選項卡的常見用法以及相關疑難問題解決方法,需要的朋友可以參考下2019-03-03

