四种模式下的产物大小和启动速度比较:
Flutter 构建过程
下面的分析都是基于 v1.5.4-hotfix.2
执行 flutter build apk
时,默认会生成 release APK,实际是执行的 sdk/bin/flutter 命令,参数为 build apk:
DART_SDK_PATH=“
F
L
U
T
T
E
R
R
O
O
T
/
b
i
n
/
c
a
c
h
e
/
d
a
r
t
−
s
d
k
"
D
A
R
T
=
"
FLUTTER_ROOT/bin/cache/dart-sdk" DART="
FLUTTERROOT/bin/cache/dart−sdk"DART="DART_SDK_PATH/bin/dart”
SNAPSHOT_PATH=“
F
L
U
T
T
E
R
R
O
O
T
/
b
i
n
/
c
a
c
h
e
/
f
l
u
t
t
e
r
t
o
o
l
s
.
s
n
a
p
s
h
o
t
"
"
FLUTTER_ROOT/bin/cache/flutter_tools.snapshot" "
FLUTTERROOT/bin/cache/fluttertools.snapshot""DART”
F
L
U
T
T
E
R
T
O
O
L
A
R
G
S
"
FLUTTER_TOOL_ARGS "
FLUTTERTOOLARGS"SNAPSHOT_PATH" “$@”
上面的命令完整应该为:dart flutter_tools.snapshot args
,snapshot 文件我们上面提过,是 Dart 的一种代码集合,类似 Java 中 Jar 包。
flutter_tools 的源码位于 sdk/packages/flutter_tools/bin 下的 flutter_tools.dart,跟 Java 一样,这里也有个 main()
函数,其中调用的是 executable.main()
函数。
在 main 函数中,会注册多个命令处理器,比如:
- DoctorCommand 对应
flutter doctor
命令 - CleanCommand 对应
flutter clean
命令 - 等等
我们这次要研究的目标是 BuildCommand,它里面又包含了以下子命令处理器:
- BuildApkCommand 对应
flutter build apk
命令 - BuildAppBundleCommand 对应
flutter build bundle
命令 - BuildAotCommand 对应
flutter build aot
命令 - 等等
Build APK
首先我们要理清 build apk 或者 build ios,和 build bundle、build aot 之间的关系。这里我们以 build apk 为例:
当执行 flutter build apk
时,最终会调用到 gradle.dart 中的 _buildGradleProjectV2()
方法,在这里最后也是调用 gradle 执行 assemble task。而在项目中的 android/app/build.gradle 中可以看到:
apply from: “$flutterRoot/packages/flutter_tools/gradle/flutter.gradle”
也就是说,会在 flutter.gradle 这里去插入一些编译 Flutter 产物的脚本。
flutter.gradle 是通过插件的形式去实现的,这个插件命名为 FlutterPlugin。这个插件的主要作用有一些几点:
- 除了默认的 debug 和 release 之外,新增了 profile、dynamicProfile、dynamicRelease 这三种 buildTypes:
project.android.buildTypes {
profile {
initWith debug
if (it.hasProperty(‘matchingFallbacks’)) {
matchingFallbacks = [‘debug’, ‘release’]
}
}
dynamicProfile {
initWith debug
if (it.hasProperty(‘matchingFallbacks’)) {
matchingFallbacks = [‘debug’, ‘release’]
}
}
dynamicRelease {
initWith debug
if (it.hasProperty(‘matchingFallbacks’)) {
matchingFallbacks = [‘debug’, ‘release’]
}
}
}
- 动态添加 flutter.jar 依赖:
private void addFlutterJarApiDependency(Project project, buildType, Task flutterX86JarTask) {
project.dependencies {
String configuration;
if (project.getConfigurations().findByName(“api”)) {
configuration = buildType.name + “Api”;
} else {
configuration = buildType.name + “Compile”;
}
add(configuration, project.files {
String buildMode = buildModeFor(buildType)
if (buildMode == “debug”) {
[flutterX86JarTask, debugFlutterJar]
} else if (buildMode == “profile”) {
profileFlutterJar
} else if (buildMode == “dynamicProfile”) {
dynamicProfileFlutterJar
} else if (buildMode == “dynamicRelease”) {
dynamicReleaseFlutterJar
} else {
releaseFlutterJar
}
})
}
}
- 动态添加第三方插件依赖:
project.dependencies {
if (project.getConfigurations().findByName(“implementation”)) {
implementation pluginProject
} else {
compile pluginProject
}
- 在 assemble task 中添加一个 FlutterTask,这个 task 非常重要,这里会去生成 Flutter 所需要的产物:
首先,当 buildType 是 profile 或 release 时,会执行 flutter build aot
:
if (buildMode == “profile” || buildMode == “release”) {
project.exec {
executable flutterExecutable.absolutePath
workingDir sourceDir
if (localEngine != null) {
args “–local-engine”, localEngine
args “–local-engine-src-path”, localEngineSrcPath
}
args “build”, “aot”
args “–suppress-analytics”
args “–quiet”
args “–target”, targetPath
args “–target-platform”, “android-arm”
args “–output-dir”, “KaTeX parse error: Expected '}', got 'EOF' at end of input: …end-options", "{extraFrontEndOptions}”
}
if (extraGenSnapshotOptions != null) {
args “–extra-gen-snapshot-options”, “KaTeX parse error: Expected 'EOF', got '}' at position 37: …ons}" }̲ …{targetPlatform}”
}
args “–${buildMode}”
}
}
其次,执行 flutter build bundle
命令,当 buildType 为 profile 或 release 时,添加额外的 --precompiled 选项。
project.exec {
executable flutterExecutable.absolutePath
workingDir sourceDir
if (localEngine != null) {
args “–local-engine”, localEngine
args “–local-engine-src-path”, localEngineSrcPath
}
args “build”, “bundle”
args “–suppress-analytics”
args “–target”, targetPath
if (verbose) {
args “–verbose”
}
if (fileSystemRoots != null) {
for (root in fileSystemRoots) {
args “–filesystem-root”, root
}
}
if (fileSystemScheme != null) {
args “–filesystem-scheme”, fileSystemScheme
}
if (trackWidgetCreation) {
args “–track-widget-creation”
}
if (compilationTraceFilePath != null) {
args “–compilation-trace-file”, compilationTraceFilePath
}
if (createPatch) {
args “–patch”
args “–build-number”, project.android.defaultConfig.versionCode
if (buildNumber != null) {
assert buildNumber == project.android.defaultConfig.versionCode
}
}
if (baselineDir != null) {
args “–baseline-dir”, baselineDir
}
if (extraFrontEndOptions != null) {
args “–extra-front-end-options”, “KaTeX parse error: Expected 'EOF', got '}' at position 40: … }̲ …{extraGenSnapshotOptions}”
}
if (targetPlatform != null) {
args “–target-platform”, “KaTeX parse error: Expected 'EOF', got '}' at position 48: … }̲ …{intermediateDir}/snapshot_blob.bin.d”
}
args “–asset-dir”, “${intermediateDir}/flutter_assets”
if (buildMode == “debug”) {
args “–debug”
}
if (buildMode == “profile” || buildMode == “dynamicProfile”) {
args “–profile”
}
if (buildMode == “release” || buildMode == “dynamicRelease”) {
args “–release”
}
if (buildMode == “dynamicProfile” || buildMode == “dynamicRelease”) {
args “–dynamic”
}
}
稍微总结下,当 buildType 为 debug 时,只需要执行:
flutter build bundle
而当 buildType 为 release 时,需要执行两个命令:
flutter build aot
flutter build bundle --precompiled
Build AOT
当执行 flutter build aot
时,相关的逻辑在 BuildAotCommand 中,它主要分成两个步骤:
- 编译 kernel。kernel 指 Dart 的一种中间语言,更多资料可以阅读 Kernel-Documentation。最终会调用到 compile.dart 中的
KernelCompiler.compile()
方法:
final List command = [
engineDartPath,
frontendServer,
‘–sdk-root’,
sdkRoot,
‘–strong’,
‘–target=$targetModel’,
];
if (trackWidgetCreation)
command.add(‘–track-widget-creation’);
if (!linkPlatformKernelIn)
command.add(‘–no-link-platform’);
if (aot) {
command.add(‘–aot’);
command.add(‘–tfa’);
}
if (targetProductVm) {
command.add(‘-Ddart.vm.product=true’);
}
if (incrementalCompilerByteStorePath != null) {
command.add(‘–incremental’);
}
Uri mainUri;
if (packagesPath != null) {
command.addAll([‘–packages’, packagesPath]);
mainUri = PackageUriMapper.findUri(mainPath, packagesPath, fileSystemScheme, fileSystemRoots);
}
if (outputFilePath != null) {
command.addAll([‘–output-dill’, outputFilePath]);
}
if (depFilePath != null && (fileSystemRoots == null || fileSystemRoots.isEmpty)) {
command.addAll([‘–depfile’, depFilePath]);
}
if (fileSystemRoots != null) {
for (String root in fileSystemRoots) {
command.addAll([‘–filesystem-root’, root]);
}
}
if (fileSystemScheme != null) {
command.addAll([‘–filesystem-scheme’, fileSystemScheme]);
}
if (initializeFromDill != null) {
command.addAll([‘–initialize-from-dill’, initializeFromDill]);
}
if (extraFrontEndOptions != null)
command.addAll(extraFrontEndOptions);
command.add(mainUri?.toString() ?? mainPath);
printTrace(command.join(’ '));
final Process server = await processManager
.start(command)
.catchError((dynamic error, StackTrace stack) {
printError(‘Failed to start frontend server $error, $stack’);
});
engineDart 指向 Dart SDK 目录,上面代码执行的最终命令可以简化为:
dart frontend_server.dart.snapshot --output-dill app.dill packages:main.dart
app.dill 这里面其实就包含了我们的业务代码了,可以使用 strings app.dill
查看:
- 生成 snpshot。相关的代码位于 base/build.dart 中的
AOTSnapshotter.build()
函数中,有两种模式:app-aot-assemble 和 app-aot-blobs。
app-aot-assemble
在执行 aot 命令时,增加 --build-shared-library
选项,完整命令如下:
flutter build aot --build-shared-library
iOS 只能使用这种模式,在 Flutter SDK 1.7.x 之后,这个也是 Android 的默认选项。
// buildSharedLibrary is ignored for iOS builds.
if (platform == TargetPlatform.ios)
buildSharedLibrary = false;
if (buildSharedLibrary && androidSdk.ndk == null) {
// 需要有 NDK 环境
final String explanation = AndroidNdk.explainMissingNdk(androidSdk.directory);
printError(
‘Could not find NDK in Android SDK at ${androidSdk.directory}:\n’
‘\n’
’ $explanation\n’
‘\n’
‘Unable to build with --build-shared-library\n’
‘To install the NDK, see instructions at https://developer.android.com/ndk/guides/’
);
return 1;
}
这种模式下,会将产物编译为二进制文件,在 iOS 上为 App.framework,Android 上则为 app.so。
// Assembly AOT snapshot.
outputPaths.add(assembly);
genSnapshotArgs.add(‘–snapshot_kind=app-aot-assembly’);
genSnapshotArgs.add(‘–assembly=$assembly’);
app-aot-blobs
当使用这种模式时,会生成四个产物,分别是:
instr 全称是 Instructions
- isolate_snapshot_data:
表示 isolate 堆存储区的初始状态和特定的信息。和 vm_snapshot_data 配合,更快的启动 Dart VM。
- isolate_snapshot_instr:
包含由 Dart isolate 执行的 AOT 代码。
- vm_snapshot_data:
表示 isolates 之间的共享的 Dart 堆存储区的初始状态,用于更快的启动 Dart VM。
- vm_snapshot_instr:
包含 VM 中所有的 isolates 之间共享的常见例程的指令
isolate_snapshot_data 和 isolate_snapshot_instr 跟业务相关,而 vm_snapshot_data 和 vm_snapshot_instr 则是跟 VM 相关,无关业务。
我们可以使用 strings
查看下 isolate_snapshot_data 中内容:
小结
上面两种模式相关的代码如下:
final String assembly = fs.path.join(outputDir.path, ‘snapshot_assembly.S’);
if (buildSharedLibrary || platform == TargetPlatform.ios) {
// Assembly AOT snapshot.
outputPaths.add(assembly);
genSnapshotArgs.add(‘–snapshot_kind=app-aot-assembly’);
genSnapshotArgs.add(‘–assembly=KaTeX parse error: Expected 'EOF', got '}' at position 89: … }̲ else { …vmSnapshotData’,
‘–isolate_snapshot_data=
i
s
o
l
a
t
e
S
n
a
p
s
h
o
t
D
a
t
a
′
,
′
−
−
v
m
s
n
a
p
s
h
o
t
i
n
s
t
r
u
c
t
i
o
n
s
=
isolateSnapshotData', '--vm_snapshot_instructions=
isolateSnapshotData′,′−−vmsnapshotinstructions=vmSnapshotInstructions’,
‘–isolate_snapshot_instructions=$isolateSnapshotInstructions’,
]);
}
从执行速度来看,app-aot-assemble 是要快于 app-aot-blobs 的,因为它不需要 Dart VM 环境,只需要 Dart Runtime 即可,而 snapshots 文件是需要 Dart VM 去加载执行的。但使用 snapshots 使得动态执行代码变成可能。
iOS 默认使用 app-aot-assemble 模式,更多是 App Store 本身的限制:
引用于flutters-compilation-patterns
App Store does not allow dispatch binary executable code.
而 Android 默认使用 app-aot-blobs 模式,可能更多是从性能方面考虑,必须调用从 so 文件中调用 native 函数,需要用 JNI,有性能损耗,而且调用也比较麻烦,不过在 Flutter SDK 1.7.x 已经改成 app-aot-assemble 模式。
Build Bundle
当执行 flutter build bundle
时,相关的代码逻辑在 BuildBundleCommand 中,build bundle 主要做两件事:第一,如果没有添加 --precompiled
选项时,会先编译 kernel;第二,生成 assets(图片、字体等)。
- 编译 kernel。这个步骤和 build aot 的第一个步骤是一样的,最终会生成 app.dill,这是业务代码编译后的产物。同时,这个会创建一个 kernelContent,这个在第二个步骤会讲到:
kernelContent = DevFSFileContent(fs.file(compilerOutput.outputFilename));
学习交流
群内有许多来自一线的技术大牛,也有在小厂或外包公司奋斗的码农,我们致力打造一个平等,高质量的Android交流圈子,不一定能短期就让每个人的技术突飞猛进,但从长远来说,眼光,格局,长远发展的方向才是最重要的。
35岁中年危机大多是因为被短期的利益牵着走,过早压榨掉了价值,如果能一开始就树立一个正确的长远的职业规划。35岁后的你只会比周围的人更值钱。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!
FSFileContent(fs.file(compilerOutput.outputFilename));
学习交流
[外链图片转存中…(img-xBrCSc0L-1715105414743)]
[外链图片转存中…(img-OEPhej9q-1715105414744)]
群内有许多来自一线的技术大牛,也有在小厂或外包公司奋斗的码农,我们致力打造一个平等,高质量的Android交流圈子,不一定能短期就让每个人的技术突飞猛进,但从长远来说,眼光,格局,长远发展的方向才是最重要的。
35岁中年危机大多是因为被短期的利益牵着走,过早压榨掉了价值,如果能一开始就树立一个正确的长远的职业规划。35岁后的你只会比周围的人更值钱。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!