flutter engine 那些沒被釋放的東西

code4flutter發表於2019-07-22

由於flutter一直存在記憶體洩漏的問題,導致很多開發者不勝困擾,博主在0.9.4就開始對其程式碼內部記憶體問題在engine層面修改程式碼,得到解決,但是對於每個版本都需要跟隨官方打包,對於開發者並不是很友好。

然而喜出望外的是,在後來的幾個版本中,官方內建開發了手動釋放記憶體的方式?


/**
 * 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物件釋放所有資源。 傳送此訊息後,物件將處於不可用狀態,直到解除分配為止。 訪問屬性或向其傳送訊息將導致未定義的行為或執行時錯誤。

但是,但是,但是,(重要的事說三遍) 在Flutter engine開發群裡面,有群友反饋還有很多問題

  1. 無法完全釋放記憶體

  2. 偶現崩潰

偶現崩潰的是什麼鬼,暫時沒有遇到,不好說。 之前博主遇到的崩潰是自己使用方式的問題,在fluttervc關閉之後還有任務在執行methodchannel,即還在呼叫plugin,這個可以在開發上避免。 值得注意的是,flutter中使用c++實現,自己對於記憶體管理並不是很好

記憶體問題自測如下

效果圖

確實存在問題,還有將近30M沒有被釋放,檢視一下當前記憶體物件,如下圖

記憶體

一個一個看還有那些沒有被釋放吧

android:LruCache

Least Recently Used 近期最少使用演算法。 記憶體管理的一種頁面置換演算法,對於在記憶體中但又不用的資料塊(記憶體塊)叫做LRU,flutter engine 會根據哪些資料屬於LRU而將其移出記憶體而騰出空間來載入另外的資料。

dart::BackgroundComplier 對isolate編譯優化的類

BackgroundCompiler 在後臺執行緒中執行優化編譯的類。 實現:每個隔離一個任務,它與擁有isolate一起消失,後臺編譯器中沒有OSR編譯。

dart::bin::socket

vm和開發平臺通訊的機制,比如jit即時編譯的dill檔案,通過socket傳遞給dart vm,vm通過rpc載入檔案,重置執行緒,從而實現hotreload熱過載

dart::BoolPrameter

  • dart::EnumParameter
  • dart::IdParameter
  • dart::IdParameter
  • dart::xxxPrameter

定義在dart vm,service.cc中,都繼承自MethodParameter,做對應引數校驗,引數解析用。編譯dart檔案用的

dart::OSThread

在dart 執行時負責作業系統執行緒,建立執行緒,移除執行緒,執行緒查詢與管理。 如下圖

flutter_os_thread

FlutterEngineRegistrar 註冊使用key註冊plugin的地方,所有plugin呼叫dart底層的方法都會通過 handlemethodcall 回撥給使用者, 其初始化的地方是引起記憶體洩漏的地方

- (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的迴圈引用 文章

FlutterStandardMethodCodec 標準方法編解碼

FlutterStringCodec string編解碼 FlutterJsonMessageCodec json編解碼

不看不知道,一看嚇一跳,也竟然是個單例,當然不會被釋放了,也能理解,在flutter中用到jsonmssage的地方很多,用不著每次都初始化

flutter_os_thread

程式碼實現的地方


@implementation FlutterJSONMessageCodec
+ (instancetype)sharedInstance {
  static id _sharedInstance = nil;
  if (!_sharedInstance) {
    _sharedInstance = [FlutterJSONMessageCodec new];
  }
  return _sharedInstance;
}
複製程式碼

std:share_ptrxxx 共享指標

指標獲取 flutter isolate service dartvm symbolmapping

flutter share ptr

~~ 文章完 ~~

如果你想深入討論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

複製程式碼

原創不易,版權所有,轉載請備註 code4flutter.com

相關文章