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?
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
As suggested by Tony:
I edited the Mysql my.ini to change the mysql service to only bind to the IPV4 loopback adapter.
[mysqld] ... bind=127.0.0.1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With