Performance Improvement: Cache Your Drupal Blocks

Posted 05/01/2009 - 10:37am by editor

Traditionally, the way to improve the performance of a Drupal site is to enable the page-level cache. While this may work well with a site that only has anonymous users, it will not be used at all for authenticated users. Drupal just can't tell whether the page contains sensitive or personalised content that should not be shared between users.

 

The approach taken with Drupal 6 module development is to use block-level caching (via hook_block). Developers can then provide much more information as to the scope of caching required. The scope levels are:

  • BLOCK_NO_CACHE
  • BLOCK_CACHE_PER_ROLE
  • BLOCK_CACHE_PER_USER
  • BLOCK_CACHE_GLOBAL

Generally, you don't want to hit the database unnecessarily. If you're block is the same for all users, consider setting the cache level to BLOCK_CACHE_GLOBAL. By default, blocks are set to BLOCK_CACHE_PER_ROLE which is fine for most cases especially if you display different content for admin users.  If you do have any personalised content in your custom module block, make sure you change the caching to BLOCK_NO_CACHE. While this will mean the database will still be hit on each request, you will avoid consuming a huge amount of caching resources for very little benefit.

Resources: