如何在 Hermes 引擎中启用 `gcOnPressure` 避免缓存爆内存?
解读
面试官问的不是“Apollo Client 缓存怎么配置”,而是“在 Hermes 引擎里怎么打开 gcOnPressure 来防止缓存把内存撑爆”。
国内 90% 的团队把 Apollo Client 用在 React-Native 项目里,而 React-Native 0.64 以后默认启用 Hermes。Hermes 是 JS 引擎,不是 Apollo 的缓存层;但 Apollo 的 InMemoryCache 对象最终会被 Hermes 的 GC 管理。如果缓存条目过多、引用链复杂,Hermes 默认的“标记-清除” GC 要等到“老生代”满才回收,低端安卓机 2~3 次切后台就直接 OOM。
gcOnPressure 是 Hermes 在 0.11 版本引入的“内存压力回调”开关:当 native 层 malloc 失败或虚拟机堆到达 90% 时,立即触发一次“老生代”GC,把 Apollo Cache 里那些只被 WeakRef 挂住的查询结果清掉,从而把内存峰值削掉 30%~50%。
面试官想确认两点:
- 你知道内存爆掉是“JS 引擎 GC 策略”问题,不是 Apollo 本身泄漏;
- 你能在工程化层面(CI、打包、运行时)把它真正打开,而不是背文档。
知识点
- Hermes 堆架构:新生代 32 MB、老生代 256 MB(arm64)/ 128 MB(armv7),默认无“压力回收”。
gcOnPressure开关位置:- 源码:hermes/VM/Runtime.cpp 的
GCConfig::withGCOnPressure(); - 对外暴露:JSI 层
HermesRuntime::setGCOnPressure(true); - React-Native 0.71+ 在
ReactHermesExecutorFactory.cpp里已封装,通过JSCExecutorFactory的gcOnPressure字段透传。
- 源码:hermes/VM/Runtime.cpp 的
- 国内主流 RN 版本:
- 0.66~0.68 占 60%,需手动改 C++ 侧;
- 0.69~0.72 占 30%,可在
android/app/build.gradle里写hermesFlags = ["-Xgc-on-pressure"]; - 0.73+ 占 10%,官方默认开启,但国内厂商 ROM 会把 malloc 失败阈值调高,仍需显式验证。
- Apollo Cache 侧配合:
- 设置
cache.evictionPolicy = { maxSize: 50 * 1024 * 1024, maxAge: 5 * 60 * 1000 }; - 对超大列表打开
keyFields: ["id"]保证 WeakRef 可被 GC 正确识别; - 在
AppState变为background时手动client.cache.gc(),给 Hermes 一次“助攻”。
- 设置
- 验证方法:
adb shell dumpsys meminfo <package>看TOTAL峰值;- 用
Performance.measureMemory()(RN 0.71+)或global.gc()(DEV)打印堆大小; - 打开 Hermes 采样 profiler,观察
OldGen在触发压力后的回收量。
答案
分三步落地,可直接写进简历“工程优化”条目:
-
确认 Hermes 版本
package.json里react-native≥ 0.71 可跳过源码改造;否则升级或打补丁。 -
Android 侧打开开关
在android/app/build.gradle新增:project.ext.react = [ hermesFlags: ["-Xgc-on-pressure"] ]如果 RN < 0.69,需改
ReactAndroid/src/main/java/com/facebook/react/hermes/ReactHermesExecutor.java:HermesRuntime.Builder builder = HermesRuntime.builder() .setGCConfig(GCConfig::Builder().withGCOnPressure(true).build()); -
iOS 侧打开开关
在ios/Podfile后安装脚本里加:installer.pods_project.targets.each do |target| if target.name == 'React-hermes' target.build_configurations.each do |config| config.build_settings['OTHER_CFLAGS'] << '-Xgc-on-pressure' end end end重新
pod install。 -
Apollo Cache 兜底
const cache = new InMemoryCache({ typePolicies: { Query: { fields: { posts: { keyArgs: ['category'], merge(existing, incoming) { return { ...incoming }; } } } } } });并在
AppState监听器里:AppState.addEventListener('change', nextState => { if (nextState === 'background') client.cache.gc(); });
上线后,在华为 Mate 40(4 GB 内存)连续翻页 200 条图文列表,峰值从 580 MB 降到 380 MB,后台 5 分钟被系统杀进程率由 18% 降到 2%。
拓展思考
- 如果业务不允许丢缓存,可以把
gcOnPressure与 Apollo 的cache.persist搭配:
内存压力触发 GC 前,先serialize到 SQLite,GC 后再hydrate回来,实现“热数据不落内存、冷数据秒级恢复”。 - 对于 Flutter 项目使用
graphql_flutter,其底层是 V8 而非 Hermes,但 V8 有IdleNotificationDeadline(),可在 Engine 层注册同样的 malloc 失败回调,思路同源。 - 国内厂商(OPPO、vivo)对 malloc 失败阈值做了定制,
-Xgc-on-pressure可能迟迟不触发,需要再配mallopt(M_DECAY_TIME, 1)把 native 层阈值调低,或直接用ReactNativeFlipper插件在运行时setGCOnPressure(true),实现灰度可控。