Search code examples
javascriptv8

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


For a javascript class with no 'fancy' stuff going on:

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.
  }
}

Is there any chance of the compiler thinking 'Huh, all the data referenced by the a.minBar call hasn't changed, I don't need to do the long calculation of the Min value again, I'll cache the result'

Because otherwise I imagine having to do an internal state caching system if I need to sort an array of Foos on their minBar value.


Solution

  • While I believe the specific term for what you're asking about is known as Memoization, it's not really something you'd expect a JS engine to support, even a modern v8 engine. As commenters in the OP point out, "checking whether the array has been modified is as expensive as finding the min", which makes sense as the engine has no way of knowing how/what has been mutated by any given method call within a property.

    From the 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

    Rather than hack away at a potentially unhelpful example, I'll instead point you to the Lodash library's memoize function. From the docs:

    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]
    

    More potentially useful for your purposes might be reading through its' implementation in the source code.