Can a cached function be called directly?

I’m looking at the Performance page

In the example below, there is a dataframe() function used to return the results of the cached function - why not use the cached function directly?

There’s no inherent reason why you can’t cache (non-callback) functions. In terms of making that decision, you probably want to think about a) when the function will need to run, and b) what parameters need to be passed into the function, and where they come from.

For a function that takes parameters, the cache will save a result for every distinct combination of parameters and corresponding values it has been called with. In your example, the function takes no parameters, so there’s only one output that needs to be cached, and since you’re not calling it from within a callback, its return value will be evaluated only once, on app start-up. So in this case you’re not actually getting any value from the cache, as the function wont be hit again. However, if the layout was assigned to a function (which would be evaluated every time a user loads the app), then the cache would be used on subsequent page loads after the first page load from a user.

If the parameters come from user actions, then those parameters will ultimately be sourced from a callback. In this case, caching the entire callback is a convenient way to cache outputs parameterised by user inputs. One situation where it would make sense to put the cache on a supporting data load function instead is if multiple callbacks make use of that function, so they can all benefit from the one shared cache.

In summary, as is often the case, it depends on your situation :slight_smile:

3 Likes