Why is constructing PDO connection slow?
Asked Answered
P

1

36

I'm using PDO in my PHP application. It connects to a MySQL server on the same server:

$db = new PDO(mysql:host=localhost;dbname=test, $username, $password);

I created two pages with the same output (just some dummy data in plain html) one of which contains the call to create PDO. If I open the page that uses no connection the response is between 0.5 and 1 second quicker.

Polycythemia answered 21/3, 2012 at 7:54 Comment(4)
How do you get data from a database without a connection?Tharp
The dummy data is just some plain HTML, nothing from the database.Polycythemia
That effect is not normal. Seems like you have server-related issues. Maybe SQL server is slow to respond. Try to investigate more, but to me this seems more like ServerFault problem.Unfold
See also $host=gethostbyname('localhost') at https://mcmap.net/q/135071/-what-are-the-disadvantages-of-using-persistent-connection-in-pdoWizened
P
83

I've been doing some googling, and after reading this thread, I changed localhost to 127.0.0.1. That solves the problem....

Polycythemia answered 21/3, 2012 at 8:13 Comment(6)
You made my day! Using localhost it took a whole second to connect, using 127.0.0.1 it takes about one millisecond.Fasano
Very helpful research. I tried to find the solution for while until this helped. Dropped from 1s to less than 3ms.Backstroke
A little 'why': By using a hostname, PHP is forced to do a lookup in the DNS table (slow!). If this is a big table, it can take a long time before the entry is found. By using a static IP address you can skip this resolving altogether. You can even do this in production with non-localhost IP's!Fornax
DNS is slow, but not THAT slow. There must be something else at play here. Same happened for me 1sec down to ms. Thanks for posting, very helpfulTeetotalism
@AshMcConnell Would you happen to be using Windows 8? I believe it's an issue in Windows 8.Gyatt
Using Win7x64 I've had the same issue- only a 21sec delay(!) Beware of localhost...Amethyst

© 2022 - 2024 — McMap. All rights reserved.