I’ve been working with React hooks recently and one of them allows you to memoize calculations. This is useful where you have a slow, or computationally expensive, function as given the same arguments you’ll get the cached result instead of recalculating each time. The same can be done in CFML code.
To demonstrate here’s simple function to simulate a slow operation
function slow( a, b ) { sleep( 1000 ); // pause for a second return a*b; }
Calling this function with the same arguments multiple times will return the same result but take the same amount of time to run each time.
We can create a memoize
function which will wrap around the slow
function and if it’s been previously called with the same arguments, it’ll return the previously calculated response instantly without needing to run the code in the slow
function.
Here’s what the memoize
function could look like:
function memoize( fn ) { var results = {}; return function() { var argsKey = serializeJSON( arguments ); if ( !structKeyExists( results, argsKey )) { results[argsKey] = fn( argumentCollection=arguments ); } return results[argsKey]; }; }
To use it with the slow
function you would do:
memoizeSlow = memoize(slow); result = memoizeSlow(10,2);
Now if we call it for a second time, with the same arguments, we will get an instant response.
s = getTickCount(); r = memoizeSlow(10,2); e = getTickCount(); writeDump({ result: r, // 20 ms: e-s // 1001 }); // call again with same args s = getTickCount(); r = memoizeSlow(10,2); e = getTickCount(); writeDump({ result: r, // 20 ms: e-s // 0 }); // call with new args s = getTickCount(); r = memoizeSlow(10,3); e = getTickCount(); writeDump({ result: r, // 30 ms: e-s // 1008 }); // call again with original args s = getTickCount(); r = memoizeSlow(10,2); e = getTickCount(); writeDump({ result: r, // 20 ms: e-s // 0 });
As you can see, we are getting the expected results, but with a performance boost.
If you always wanted the slow
function to work this way you could skip the intermediate step and just pass the function in directly like so:
memoizeSlow = memoize( function( a, b ) { sleep(1000); return a*b; });
Here is some runnable code if you want to play around with it:
https://cffiddle.org/app/file?filepath=bb1d967e-2431-4d72-9977-c5bafd4df1ae/71ecd970-6f51-44a7-b1a2-137c9c7b6205/5193e14b-ae30-4724-aac8-cce15357004c.cfm
The post memoize functions in CFML appeared first on ColdFusion.