预编译 v8 脚本以用于多个隔离

Precompile v8 script for use in multiple isolate

我已经使用嵌入式 v8 实现了一个类似 'require' 的函数,它加载一个 JavaScript 文件并执行它,但是因为我的程序有多个线程,因此每个线程都有自己的 isolate ,我必须在指定相同源的每个线程中分别加载和编译文件。如果可能的话,我想以某种方式缓存任何已编译的脚本,以便如果另一个线程(使用另一个隔离区)恰好需要相同的文件,我可以利用某种预编译格式,并将脚本提供给 运行,而不必在需要相同文件的每个隔离区内单独编译它。

我不明白这怎么可能,所有代码、脚本、SharedFunctionInfo 等都是 JavaScript 特定于 isolate 的对象。

然而,您可以构建某个 V8 状态的静态快照,并让所有隔离始终加载该状态,但这不能在运行时动态加载。这就是 V8 内置函数的作用。

我认为 ScriptCompiler 可以帮助您。使用 ScriptCompiler::CompileUnboundScript 您可以为脚本创建和使用缓存数据。我(还)没有测试它,但评论看起来很有希望:

/**
   * Compiles the specified script (context-independent).
   * Cached data as part of the source object can be optionally produced to be
   * consumed later to speed up compilation of identical source scripts.
   *
   * Note that when producing cached data, the source must point to NULL for
   * cached data. When consuming cached data, the cached data must have been
   * produced by the same version of V8.
   *
   * \param source Script source code.
   * \return Compiled script object (context independent; for running it must be
   *   bound to a context).
   */