如果 class 属性不变,现代 JavaScript (V8) 是否会对 Class 方法进行任何缓存?

Does modern JavaScript (V8) do any caching of Class methods if class properties don't change?

对于 javascript class 没有 'fancy' 事情发生:

class Foo {
  nums = [1,4,3,8,9.2];

  get minBar() {
    return Math.min(...this.nums); // Pretend this is a function that takes much more time.
  }
}

编译器有没有可能认为'嗯,a.minBar 调用引用的所有数据都没有改变,我不需要再次对 Min 值进行长时间计算,我'将缓存结果'

否则我想如果我需要根据 minBar 值对 Foos 数组进行排序,则必须执行内部状态缓存系统。

虽然我相信您所询问的特定术语被称为 Memoization,但它并不是您真正期望 JS 引擎支持的东西,即使是现代 v8 引擎也是如此。正如 OP 中的评论者指出的那样,"checking whether the array has been modified is as expensive as finding the min" 是有道理的,因为引擎无法知道 how/what 已被 属性.[=16= 中的任何给定方法调用所改变。 ]

来自link:

memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again

我不会讨论一个可能无用的示例,而是会向您指出 Lodash 库的 memoize 函数。来自文档:

Creates a function that memoizes the result of func. If resolver is provided, it determines the cache key for storing the result based on the arguments provided to the memoized function. By default, the first argument provided to the memoized function is used as the map cache key. The func is invoked with the this binding of the memoized function.

var object = { 'a': 1, 'b': 2 };
var other = { 'c': 3, 'd': 4 };

var values = _.memoize(_.values);
values(object);
// => [1, 2]

阅读源代码中的 implementation 可能对您的目的更有用。