In this article, we will learn the benefits of persistent connection in PDO, in terms of memory usage and time of execution.
The article will only observe connection to MySQL database.

Introduction

PDO is an abstraction layer for database connections in PHP, and it became increasingly popular in the past few years.

PDO gives us the option to use a persistent connection.
If we don’t use this option, a new connection is created for each request.
If we do use this option, the connection is not closed at the end of the script, and it is then re-used by other script requests.

Connection to the database using this option is not very different from a regular connection:

$pdo = new PDO('mysql:dbname=database;host=127.0.0.1', 'username', 'password'); // Regular connection
$pdo = new PDO('mysql:dbname=database;host=127.0.0.1', 'username', 'password', array(PDO::ATTR_PERSISTENT => true)); // Persistent connection

Testing Environment

All of tests ran on my PC using zend server.
CPU: Intel E8400
RAM: 4GB DDR2 800MHz
I used a MySQL database with root permissions, with an empty database named pdotest.

Memory Usage

In order to test the memory usage I wrote two simple scripts, which establish a connection and print the memory difference between the time before the connection was created to the time after it.
The results indicates that the persistent connection consumed 18.5 times less memory than the non-persistent connection.
The non-persistent connection used 6232 bytes while the persistent connection used 336 bytes.

Requests per Second

In order to test the speed of the connection I used Apache’s ab tool.
I tested both methods with 1, 2, 3, 5, 10, 50 and 100 concurrent users, for 10 seconds every time.
Test results show that the persistent connection gave 6.3 to 1.5 times more requests per second than the non-persistent version.

Conclusions

The results are clear, persistent connection uses less memory and runs faster.
You can download the test files and the full results here.

Tagged with:
 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Set your Twitter account name in your settings to use the TwitterBar Section.