简体   繁体   中英

CURL resolving hosts much slower than plain file_get_contents

I'm getting a service response by URL on localhost. When using CURL and using "localhost" as the domain name the first request takes about 150ms, second request takes 2ms. When using IP instead of "localhost" both CURL requests take 2ms. When using file_get_contents it's always about 3ms no matter if it's "localhost" or IP.

What can cause such a delay even for localhost?

Here is the test code:

$instance['port'] = 8192;
$instance['hostname' ] = 'localhost';
//$instance['hostname' ] = '127.0.0.1';


/* file_get_contents */
$time = microtime(true);
$response = file_get_contents('http://'.$instance['hostname' ].':'.$instance['port'].'/file1.txt');
$queryTime = microtime(true) - $time;
echo "file_get_contents time: ".$queryTime."<br>";

$time = microtime(true);
$response = file_get_contents('http://'.$instance['hostname' ].':'.$instance['port'].'/file2.txt');
$queryTime = microtime(true) - $time;
echo "file_get_contents time: ".$queryTime."<br><br>";


/* CURL */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://'.$instance['hostname' ].':'.$instance['port'].'/file1.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$time = microtime(true);    
curl_exec($ch);
$queryTime = microtime(true) - $time;
echo "CURL time: ".$queryTime."<br>";


curl_setopt($ch, CURLOPT_URL, 'http://'.$instance['hostname' ].':'.$instance['port'].'/file2.txt');
$time = microtime(true);    
curl_exec($ch);
$queryTime = microtime(true) - $time;
echo "CURL time: ".$queryTime."<br><br>";
curl_close($ch);

Response:

file_get_contents time: 0.0029559135437012
file_get_contents time: 0.0030159950256348

CURL time: 0.15396809577942
CURL time: 0.002269983291626

When using IP instead of localhost the response is the following:

file_get_contents time: 0.0025560855865479
file_get_contents time: 0.0034060478210449

CURL time: 0.0026850700378418
CURL time: 0.0027031898498535

As said here , this is possibly DNS lookup problem. Have you tried to add localhost to your etc/hosts file?

This answer also suggests that editing hhtpd.conf might help you.

I tried your script and it works fine. First curl call a little slower. My guessing but check if you have IPv6 active, which localhost translates into.

Try to deactivate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM