Skip to content

Instantly share code, notes, and snippets.

@JamoCA
Last active March 13, 2023 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamoCA/62f8535cfcf5dacd4e7f5ea678038330 to your computer and use it in GitHub Desktop.
Save JamoCA/62f8535cfcf5dacd4e7f5ea678038330 to your computer and use it in GitHub Desktop.
Caching repetitive UDF access to request scope using argument stringified+hashed key - #ColdFusion #cfml
<!--- 20221208 Caching repetitive UDF access to request scope using argument stringified+hashed key #ColdFusion #cfml
By James Moberg / SunStar Media
GIST: https://gist.github.com/JamoCA/62f8535cfcf5dacd4e7f5ea678038330
TWEET: https://twitter.com/gamesover/status/1600908166426136576
BLOG: https://dev.to/gamesover/caching-repetitive-udf-access-to-request-scope-using-argument-stringifiedhashed-key-4fd6
--->
<cfscript>
string function slowFunction(required a, b="100", c="abc", d=[], e={}) hint="I perform a repetitive function with a cacheable result" {
// generate a unique key based on stringified+hashed arguments passed to UDF
local.cachekey = "udf_slowFunction_#arguments.toString().hashCode()#";
// if key exists within request scope, return value
if (structkeyexists(request, local.cachekey)){
return request[local.cachekey];
}
// Perform business logic (DB operations, file system, etc)
sleep(1000);
local.result = "#local.cachekey# = #arguments.toString()#";
// copy return response to request scope
request[local.cachekey] = local.result;
return request[local.cachekey];
}
for (a=1; a lte 3; a+=1){
writeoutput("<h3>Iteration #a#</h3><ol>");
for (i=1; i lte 3; i+=1){
t = gettickcount();
result = slowFunction(a);
writeoutput("<li><b>#gettickcount()-t# ms:</b> #result#</li>");
}
writeoutput("</ol>");
}
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment