
This is an object-oriented Servoy tutorial on how to use function memoization with Servoy. Function memoization uses a local object to build a cache and can improve code performance, avoiding methods from calculating the same thing over and over again. Suppose you have a function that takes in an item id and will then perform a bunch of calculations. If you performed the calculation for a given item already, function memoization allows you to grab the previously computed result and return it, instantly, rather than running through hundreds of lines of code that will compute the same result.
Here is an example of how to add function memoization to an existing method:
/** * A very long and computational heavy method * * @param {String} sItemUUID - imaginary item uuid * @param {String} [subMethod] - submethod to run (clearCache) */ function computeItemStatistics(sItemUUID, subMethod){ // If a cache has not been setup, set it up now if (!this.cache){ this.cache = {}; } // This allows us to dump the cache if (subMethod && subMethod === "clearCache"){ this.cache = null; application.output("cache cleared"); return null; } // Return the info if the item is already in the cache if (sItemUUID in this.cache){ application.output("Returning item from cache"); // returning an object containing the computed data return this.cache[sItemUUID]; } /* * Lots of complex code */ // At the end of the method, save the item info to the cache application.output("Adding " + sItemUUID + " to cache"); this.cache[sItemUUID] = { computedValue1: null, // store your values here computedValue2: null, computedValue3: null // etc. }; // method always returns the same object structure with computed results return this.cache[sItemUUID]; }
Everything in JavaScript is an object, and functions are no exception. Function memoization takes advantage of this, retaining the cached data even after the function has returned. Each time the function is called, the cache is there and accessible to all code in your function.
I want to mention that you should never use more than one cache per function, because function memoization stores the values in “this”, which points to the object that the function belongs to. So you can only have one cache active per function, but you can store a lot of information in that cache, since the cache is an object, and you can store more objects inside it.
Function memoization is a great way to quickly convert some inefficient legacy code and improve performance.