1

I have been using this snippet lately here and there, but after re-thinking , it seems like it could be a good example of over-engineered code:

<?php
function my_module_function() {
  $my_data = &drupal_static(__FUNCTION__);
   if (!isset($my_data)) {
    if ($cache = cache_get('my_module_data')) {
      $my_data = $cache->data;
    }
    else {
      // Do your expensive calculations here, and populate $my_data
      // with the correct stuff..
      cache_set('my_module_data', $my_data, 'cache');
    }
  }
  return $my_data;
}
?>

Is this truly an optimal way to cache things? I am not clear on the low-ends of it all but it seems the drupal_static call is overhead since the static call would get only called once before the data would be cached. Maybe I am seeing it wrong, and rather the cached variable would be set static for the whole request, and static access is faster than cache access?

I am also not clear if the cache is global for all users or on a per user basis. I would imagine the cache is global, but please correct me if I am wrong!.

1
2

I don't see this a overkill.

drupal_static() caches results over the lifetime of a single request. It is typically used for things that may be needed several times during page generation, but will (likely) not change. For example, if a node is loaded, it gets saved in memory in case multiple functions need it.

cache_set() / cache_get() caches things in the database (or another storage backend with the proper module), so the data persists (up to the TTL) between page requests. This gets used for things that change infrequently, and is global for all requests. As far as I can remember, the normal implementation always goes out to the cache backend and doesn't store results in memory with drupal_static() or static.

Given the overhead, I would be judicious as to whether caching really improves things.

2
  • 1
    So this pretty much answers my question. I realised after a bit of pondering and reading up codebase the power and exact purpose of drupal_static & the purpose (and difference) of cache_* functions. As you mentionned, there is some associated overhead with caching so I assume only costly functions (node loads, user profiles, custom fields) should benefit from this. I think to have a better idea, I will be comparing benchmarks with a few sample functions in a slapped up stand-alone drupal-bootstrapped script I have that lives to benchmark these things in a quick and dirty way. Thanks friend. Oct 4 '12 at 3:26
  • And don't forget, you can put caches that would go into the database (by default) into other, waaaay faster cache backends like Redis or memcached, and the overhead almost disappears. May 16 '14 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.