Reduced Drupal bootstrap for better performance

Reduced Drupal bootstrap for better performance

Submitted by Jitesh Doshi on Fri, 11/02/2012 - 18:39

Did you know you can use Drupal in your custom PHP scripts, outside of modules? Possibly. But did you know that you can make your scripts much faster by reducing Drupal's bootstrap levein your scripts? Read on to see how.

The following script reads the first 20 nids (node-ids) from your Drupal database.

require_once DRUPAL_ROOT . '/includes/'; 
drupal_bootstrap( DRUPAL_BOOTSTRAP_FULL ); 
$rows = db_select('node')
  ->fields('node', array('nid', 'title'))
  ->range(0, 20)
// Read a few records from the database and return them as JSON. 
header('Content-Type: application/json'); 
print json_encode($rows);

The above code is how normal index.php of Drupal bootstraps itself. But in our script since we are interested only in reading from the database and not running complete Drupal modules, we can get away with bootstrapping Drupal partially. So if you change the bootstrap level above from  DRUPAL_BOOTSTRAP_FULL  to  DRUPAL_BOOTSTRAP_DATABASE , the script will still function correctly. But the execution time of such a script will fall quite significantly.

How significantly? I ran a simple benchmark of 50 requests using ab (Apache Benchmark tool) with the following command.

ab -n 50 http://localhost/script.php

And I got an average request time of 206ms when the bootstrap level was from  DRUPAL_BOOTSTRAP_FULL . Upon reducing the bootstrap level to  DRUPAL_BOOTSTRAP_DATABASE , the average request time fell to 27ms ! That's how significant.

So the next time you need a high-performance PHP script that uses Drupal, consider lowering the bootstrap level for improved performance. You can read more about Drupal bootstrap levels here .

Jitesh Doshi

Profile picture for user Jitesh Doshi
Managing Partner & CTO
  • A seasoned technology entrepreneur and enthusiast
  • A regular speaker at industry conferences and universities
  • Host and organizer of technology user groups
  • Active in management of non-profit organizations serving the local community
  • Leader and contributor for multiple open-source projects
  • Expert in cloud, application integration, web and mobile technologies
  • Author of open-source projects, including on - Popular Tags and PRLP.
  • Developed several highly successful software platforms and frameworks for clients