Crayl Crayl - 6 days ago 5
MySQL Question

Why is my MySQLi connection so slow?

It takes for my local system about 1 second to establish a MySQLi connection. Code:

$db = new mysqli( 'localhost', 'root', 'pass', 'mydb' );


Why is it so slow? Is this normal? Can I improve it?

Answer

Switch "localhost" to 127.0.0.1.

So, instead of:

$db = new mysqli( 'localhost', 'root', 'pass', 'mydb');

Use:

$db = new mysqli( '127.0.0.1', 'root', 'pass', 'mydb');

Seeing as this question seems to be pretty popular and a lot of people would like to know WHY this is happening:

This is caused because the MySQL client will do an IPV6 lookup for the hostname. If this fails (and in this case, it obviously does), it will then attempt to do an IPV4 lookup. Between the IPV6 (AAAA) lookup failing and the IPV4 (A) lookup succeeding, what we get is a connection timeout cycle that lasts about 1-2 seconds.

Worth noting that this problem only seems to occur with Windows 7 and after. Before Windows 7, localhost resolution was handled by the hosts file, which came pre-configured with 127.0.0.1

Comments