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