Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache results for functions?

In Javascript, is there a way to cache results for functions that are:

  • a). Computationally expensive.
  • b). Called multiple times.

Take for example a recursive factorial function that gets called frequently. Usually I'd create a separate array such as facotrialResults = []; and add my results to them when I calculate them, factorialResults[x] = result; However, is there a better way to accomplish this caching without the use of adding a new variable to the global namespace?

like image 371
Ivan Avatar asked Jul 25 '12 23:07

Ivan


People also ask

Does Python cache function result?

Memoization allows you to optimize a Python function by caching its output based on the parameters you supply to it. Once you memoize a function, it will only compute its output once for each set of parameters you call it with. Every call after the first will be quickly retrieved from a cache.

What is cache result?

A result cache is an area of memory, either in the Shared Global Area (SGA) or client application memory, that stores the results of a database query or query block for reuse. The cached rows are shared across SQL statements and sessions unless they become stale.

What is cache in function?

The data in a cache is generally stored in fast access hardware such as RAM (Random-access memory) and may also be used in correlation with a software component. A cache's primary purpose is to increase data retrieval performance by reducing the need to access the underlying slower storage layer.

Can caching work on any function?

cache can do much more (it works on function with any arguments, properties, any type of methods, and even classes...).


1 Answers

You could attach a hash to the function that you want to cache.

var expensive_fn = function(val) {
  var result = arguments.callee.cache[val];
  if(result == null || result == undefined) {
    //do the work and set result=...
    arguments.callee.cache[val]=result;
  }
  return result;
}
expensive_fn.cache = {};

This would require that the function is a 1-1 function with no side effects.

like image 50
matsko Avatar answered Nov 05 '22 03:11

matsko