Use cache_set and cache_get


/**
 * Demo cache.
 * 
 * Get all articles from cache table
 * or load them using node_load when cache isn't set.
 * 
 * Time example is for 50 articles.
 */
function _demo_cache() {
 
  if(!cache_get('demo_cached_articles')) {
    timer_start('Demo cache -- No cache');
  
    $nids = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->execute()->fetchCol();
   
    $nodes = node_load_multiple($nids);
 
    // Average is 22 ms to load 50 articles.
    dpm(timer_stop('Demo cache -- No cache'));
    
    // Sure, cache_set also slows down page load.
    // However, if caching is used wisely,
    // this is a small price to pay.
    cache_set('demo_cached_articles', $nodes, 'cache', CACHE_TEMPORARY);
    
    return $nodes;
    
  } else {
    timer_start('Demo cache -- Cached');
    
    $cached = cache_get('demo_cached_articles');
    
    // Average is 6 ms to load 50 articles.
    dpm(timer_stop('Demo cache -- Cached'));
    
    return $cached->data;
  }
}

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.