RN系列-使用Hermes的字节码功能提升冷启动速度

1,061 阅读2分钟

1.为什么要用Hermes引擎

rn被人诟病最多的就是的缓慢js解析时间,尤其是在冷启动时动辄解析几mb大小的bundle包,在稍微好点的机器上勉强还算合格,但是在低端机上表现真的是令人咋舌,如今rn版本也升级到了0.70,hermes已经是默认的js引擎,为我们带来了更快的解析速度、更小的包体积、更低的内存占用

image.png

更重要的是解决了jsc在不同机型上的不一致性,尤其在三星机型上出现的崩溃

image.png

2.Hermes字节码性能

机型三星s10 plus

使用字节码:

  • 公共包加载耗时: 211 ms
  • 首屏渲染第一帧耗时: 766 ms

image.png

不使用字节码:

  • 公共包加载耗时: 206 ms
  • 首屏渲染第一帧耗时: 2024 ms

image.png

在公共包加载上几乎一致,应该是因为我开启了内联加载inlineRequires的原因,贴一下metro内联加载配置

/**
 * Metro configuration for React Native
 * https://github.com/facebook/react-native
 *
 * @format
 */

const { getDefaultConfig } = require('metro-config');

module.exports = (async () => {
  const {
    resolver: { sourceExts, assetExts },
  } = await getDefaultConfig();
  return {
    transformer: {
      babelTransformerPath: require.resolve('react-native-svg-transformer'),
      getTransformOptions: () => ({
        transform: {
          experimentalImportSupport: false,
          inlineRequires: true,
        },
      }),
    },
    resolver: {
      assetExts: assetExts.filter(ext => ext !== 'svg'),
      sourceExts: [...sourceExts, 'svg'],
    },
  };
})();

在首页渲染第一帧上快了2.6倍(肉眼感觉在低端机可以快更多),速度有明显的提升,缺点就是包体积大了20%左右,我个人认为完全可以接受。

3.如何将jsbundle转换为字节码

// mac
root/node_modules/react-native/sdks/hermesc/osx-bin/hermesc -emit-binary -out out.hbc in.bundle

// windows
root/node_modules/react-native/sdks/hermesc/win64-bin/hermesc.exe -emit-binary -out out.hbc in.bundle

// linux
root/node_modules/react-native/sdks/hermesc/linux64-bin/hermesc -emit-binary -out out.hbc in.bundle

out.hbc为转换后的字节码文件路径 in.bundle为正常打包生成的jsbundle路径 最后将out.hbc重命名为in.bundle 替换原本的jsbundle就大功告成