Servoy Tutorial: Function Memoization

Servoy Tutorial: Function Memoization

Servoy Tutorial Photo Credit: Reigh LeBlanc via Compfight

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:

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.

Gary Dotzlaw
Gary Dotzlaw has 20+ years of experience as a professional software developer and has worked with over 100 companies throughout the USA and Canada. Gary has extensive qualifications in all facets of the project life cycle, including initial feasibility analysis, conceptual design, technical design, development, implementation and deployment. Gary is an expert Servoy Developer, with extensive large-commercial project experience, and has written numerous advanced tutorials on Servoy development.