Reduced Drupal bootstrap for better performance
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.
<?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 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 .