2

Now I have a config file as follows:

<?php
return array(
    'server'=>'localhost',
    'username'=>'root',
    'password'=>'123456',
    'dbname'=>'duxiu',
    'charset'=>'utf8'
);

I'm cunfused about the time it spends when I using tow methods to connect mysql follows:

1.

<?php
class Mysql{
    private $conn;

    public function __construct($c){
        $this->conn=mysql_connect($c['server'],$c['username'],$c['password'],true) or die("连接出错");   
        mysql_select_db($c['dbname'],$this->conn);
        if(isset($c['charset'])){
            mysql_query("set names ".$c['charset'],$this->conn);
        }
    }
}
$c=require('config.php');
var_dump($c);
$db=new Mysql($c);

It spends 1.012 second.

2.when I using as following:

<?php
class Mysql{
    private $conn;

    public function __construct($c){
        $this->conn=mysql_connect($c['server'],$c['username'],$c['password'],true) or die("connect error");   
        mysql_select_db($c['dbname'],$this->conn);
        if(isset($c['charset'])){
            mysql_query("set names ".$c['charset'],$this->conn);
        }
    }
}
$c=array('server'=>'127.0.0.1','username'=>'root','password'=>'123456','dbname'=>'duxiu','charset'=>'utf8');
var_dump($c);
$db=new Mysql($c);

Now it spends 0.012 second .

Why?

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
bblost
  • 21
  • 2
  • mysql special-cases `localhost` to ALWAYS mean using a unix-domain local socket, whereas using `127.0.0.1` uses a TCP socket. – Marc B Apr 21 '13 at 17:55

1 Answers1

1

Difference: When you are using 127.0.0.1 instead of localhost, PHP will try to establish a TCP connection to mysql rather than using a UNIX domain socket.

Regulary it should be faster to use UNIX domain sockets but it seems in your application this is not the case as it takes very long to connect using the UNIX domain socket. Have you modified the php.ini value mysql.default_socket or pdo_mysql.default_socket? It should be empty by default. If not can you post that value?

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • Can you describe why the UNIX domain socket was that slow? – hek2mgl Apr 21 '13 at 18:09
  • My php.ini config is mysql.default_socket = "MySQL" pdo_mysql.default_socket = "MySQL" . – bblost Apr 21 '13 at 18:14
  • But I modyfy as follows mysql.default_socket = "" pdo_mysql.default_socket = "" or I close it using ; It's still slow... – bblost Apr 21 '13 at 18:18
  • What is the output of `var_dump(ini_get('mysql.default_socket'));` ? – hek2mgl Apr 21 '13 at 18:23
  • On Windows there are no domain sockets. So it should just ignore that and use TCP even if you use `localhost`. I don't know whats wrong with that on your machine. Check [this](http://stackoverflow.com/a/12600684/171318) answer? does it help? However: use 127.0.0.1 .. – hek2mgl Apr 21 '13 at 18:31