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.

user254875486
  • 11,190
  • 7
  • 36
  • 65

1 Answers1

82

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

user254875486
  • 11,190
  • 7
  • 36
  • 65
  • 2
    You made my day! Using localhost it took a whole second to connect, using 127.0.0.1 it takes about one millisecond. – CodeZombie Feb 08 '13 at 00:41
  • 1
    Very helpful research. I tried to find the solution for while until this helped. Dropped from 1s to less than 3ms. – Repeat Spacer Jul 29 '13 at 19:30
  • 10
    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! – Gerben Aug 01 '13 at 14:33
  • 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 helpful – Ash McConnell Aug 08 '14 at 12:47
  • @AshMcConnell Would you happen to be using Windows 8? I believe it's an issue in Windows 8. – mpen Sep 16 '14 at 22:13
  • Using Win7x64 I've had the same issue- only a 21sec delay(!) Beware of localhost... – andig Jan 10 '15 at 16:15