Reduced Drupal Bootstrap for Better Performance

2012-11-02

Jitesh Doshi

Reduced Drupal Bootstrap for Better Performance

How to reduce Drupal bootstrap level for improved performance in custom PHP scripts.

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 scriptsmuchfaster 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.

<?php 
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']); 
require_once DRUPAL_ROOT . '/includes/bootstrap.inc'; 
drupal_bootstrap( DRUPAL_BOOTSTRAP_FULL ); 
$rows = db_select('node')
  ->fields('node', array('nid', 'title'))
  ->range(0, 20)
  ->execute()
  ->fetchAll();
// 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 fromDRUPAL_BOOTSTRAP_FULLtoDRUPAL_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 usingab(Apache Benchmark tool) with the following command.

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

And I got an average request time of206mswhen the bootstrap level wasfromDRUPAL_BOOTSTRAP_FULL. Upon reducing the bootstrap level toDRUPAL_BOOTSTRAP_DATABASE, the averagerequesttime fell to27ms! 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 levelshere.