Caching the Result of a Function Based on its Arguments
I may be overthinking this, you be the judge...
Let's say that you have created a nice function that does its job well but takes a little more time to process than you'd like. The solution is to cache the function result. That sort of caching code is normally pretty straight forward but let's also say that you want the function itself to be responsible for whether or not its result can be cached. Here's some code I created to deal with this situation:
So, what's going on here?
The interesting code is on lines 32-34. This is where we create they key for the cache. We first take the entire arguments struct and turn it into JSON. We don't do this because we plan on using it in JavaScript, it's just an efficient way to turn whatever is passed in as arguments (including complex values) into a string representation instead. Then we strip out some characters that represents the start and end of arrays and structs, sort the results and finally hash it. The reason we strip out those characters and sort the results is because the order of the arguments in the arguments struct cannot be guaranteed (at least not in ColdFusion 8) but we need the cache key to be the same regardless of order.
Obviously this sort of caching can only be applied to functions that produce the exact same results each time when given identical arguments. For example, any function that sets variables based on the current time or gets values from the database is therefore not a good candidate for this.
What do you think of this approach, are there any better ways to accomplish the same thing?