2

To interpret a normal PHP file (without using MySQL) it takes about 0.01 Milliseconds. But if you add mysql_connect() or mysqli_connect() or any other function to connect to a DB it takes much more time to interpret it. (usually about 1.05 Miliseconds).

I've tested so many times, the problem occurs when connecting to the database. No matter how many queries you run, they're super-fast. But Why connecting to a database is slower than querying from it.

What's the problem here ? What's the fastest way to connect to MySQL ?

I am using XAMP with Apache & MySQL on Windows 7

4

1 に答える 1

5

When you connect to MySQL you are opening a socket connection. This is routed through the network layer of your operating system, and there is a handshake to perform for every connection where the client (your code) passes the username and password, and the database engine has to validate those credentials. Then the client opens a connection to a specific database.

This is known as the "overhead" of opening a database connection.

The best solutions are, (a) don't worry about a 1ms delay in your code, there are probably other ways you can get that performance benefit back, and/or the user won't even notice that 1ms; or (b) if you really really must have it micro-optimised, then you only connect once per page, or not at all if you don't need the connection on that particular page.

于 2013-02-03T04:59:23.333 に答える