javascript - 如果类属性不改变,现代 JavaScript (V8) 是否会对类方法进行缓存?

标签 javascript v8

对于没有“花哨”东西的 JavaScript 类:

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 值进行长时间的计算”再次,我将缓存结果'

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

最佳答案

虽然我相信您所询问的具体术语被称为 Memoization ,这并不是你真正期望 JS 引擎支持的东西,即使是现代的 v8 引擎也是如此。正如OP中的评论者指出的那样,“检查数组是否已被修改与查找最小值一样昂贵”,这是有道理的,因为引擎无法知道属性中的任何给定方法调用如何/改变了什么.

来自链接:

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库的内存功能。来自文档:

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在源代码中。

关于javascript - 如果类属性不改变,现代 JavaScript (V8) 是否会对类方法进行缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54953809/

相关文章:

javascript - 在 Node.js 中的变量中插入 ASCII

v8 - V8 是如何管理对象实例的内存的?

javascript - 嵌入 C++ 程序的 javascript 能否比网络上的 javascript 更快

javascript - Undersore 的 _.now 如何运作?

c# - 如何捕获 ClearScript.V8 中的更新事件?

Javascript - 函数工作一次,但再也不会

javascript - 在随机位置写入文本

javascript - 使用 onClick 从数组中删除元素并使用react

javascript - 如何简化 VueJS 的这段代码

javascript - 如何消除 "' NewInstance' is deprecated"warning in `node-gyp rebuild`?v8 中 NewInstance 的替代方案是什么?