Reputation: 1911
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?
Upvotes: 10
Views: 8432
Reputation: 19879
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
Upvotes: 41
Reputation: 6222
Another option is to edit the hosts file, found under windows\system32\drivers\etc
# localhost name resolution is handled within DNS itself.
127.0.0.1 localhost
# ::1 localhost
Use an editor with admin rights to uncomment 127.0.0.1.
Upvotes: 2
Reputation: 57312
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
Upvotes: 3