If I have MySQL running on a Linux box, is it faster to run queries if connected to localhost than if I connect to a domain which resolves to the same box? This is from Java using JDBC.
问题:
回答1:
Directly using the IP address of any interface on the localhost - either the loopback interface (127.0.0.1) or any other - is the option with the absolutely best performance. The packets will be actually routed through the loopback interface (no matter which IP is actually used) at - practically - CPU speed.
There are three reasons, however, to prefer 127.0.0.1 over the IPs of the other interfaces:
The loopback interface is crucial to the operation of the system and as such it is initialized very early in the boot process and nearly always available.
It is not affected by external factors: while removing the eth0 cable will not by itself interrupt localhost's access to itself via eth0's IP, it will mess things up if you have any of the many "autoconfiguration" systems that will happily shutdown the interface on link loss.
If you have a firewall setup, it's quite possible that the rule chain is longer (and thus slightly worse performance-wise) when the IPs of the public interfaces are involved.
If you are using hostnames, the localhost hostname will be normally resolved by an /etc/hosts lookup which is very fast, although using the IP directly removes this lookup altogether. Depending on your setup it many also be cached in memory so that it's almost blindingly fast later on.
If you use a public hostname, this may involve a DNS query which implies added CPU usage and network latency. Using a caching name server on the local host will mostly remove this issue. Keep in mind, however, that there might still be a problem if your DNS service becomes flaky.
The one advantage of using a public hostname would be if it's something like db.example.com. which allows you to move your database to a separate server without having to change the configuration of the clients.
Since you are using JDBC, I presume that you are reusing a single connection for all of your queries, in which case the hostname resolving overhead itself should be negligible in all cases, unless you have to deal with a broken DNS server. There might be still some merit in choosing the 127.0.0.1 address for its potentially more efficient firewall setup, though.
回答2:
localhost
is a domain that resolves to your computer, so I'd say that it's exactly as fast.
Using a file socket might bring in a difference, though I don't know if JDBC supports it.