Chapter 21. Performance Tuning and Load Testing

Introduction

PHP is pretty speedy. Usually, the slow parts of your PHP programs have to do with external resources—waiting for a database query to finish or for the contents of a remote URL to be retrieved. That said, your PHP code itself may not be as efficient as it could be. This chapter is about techniques for finding and fixing performance problems in your code.

There’s plenty of debate in the world of software engineeering about the best time in the development process to start optimizing. Optimize too early and you’ll spend too much time nitpicking over details that may not be important in the big picture; optimize too late and you may find that you have to rewrite large chunks of your application.

A failsafe approach to this dilemma is to get into the habit of making good choices about approaching small problems; the benefits will add up in the end. Example 21-1 shows three ways to produce the exact same MD5 hash in PHP 5.1.2.

Example 21-1. Hashing three ways
// PHP's basic md5() function
$hashA = md5('optimize this!');

// MD5 by way of the mhash extension
$hashB = bin2hex(mhash(MHASH_MD5, 'optimize this!'));

// MD5 with the hash() function in PHP 5.1.2+
$hashC = hash('md5', 'optimize this!');

$hashA, $hashB, and $hashC are all 83f0bb25be8de9106700840d66f261cf. However, the third approach is over twice as fast as PHP’s basic md5() function.

The dark side of optimization with head-to-head tests like these, though, is ...

Get PHP Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.