我是否应该关闭 cURL?

2022-08-30 16:10:11

我有一个函数,它使用cURL多次调用3个不同的API。每个 API 的结果都传递到嵌套循环中调用的下一个 API,因此 cURL 当前打开和关闭了 500 多次。

我应该让整个函数的cURL保持打开状态,还是在一个函数中多次打开和关闭它?


答案 1

重用同一句柄可以提高性能。请参见: 重复使用相同的卷曲手柄。性能大幅提升?

如果您不需要请求是同步的,请考虑使用curl_multi_*函数(例如curl_multi_initcurl_multi_exec等),这些函数还可以大大提高性能。

更新:

我尝试了对每个请求使用新句柄,并对以下代码使用相同的句柄来运行curl:

ob_start(); //Trying to avoid setting as many curl options as possible
$start_time = microtime(true);
for ($i = 0; $i < 100; ++$i) {
    $rand = rand();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://www.google.com/?rand=" . $rand);
    curl_exec($ch);
    curl_close($ch);
}
$end_time = microtime(true);
ob_end_clean();
echo 'Curl without handle reuse: ' . ($end_time - $start_time) . '<br>';

ob_start(); //Trying to avoid setting as many curl options as possible
$start_time = microtime(true);
$ch = curl_init();
for ($i = 0; $i < 100; ++$i) {
    $rand = rand();
    curl_setopt($ch, CURLOPT_URL, "http://www.google.com/?rand=" . $rand);
    curl_exec($ch);
}
curl_close($ch);
$end_time = microtime(true);
ob_end_clean();
echo 'Curl with handle reuse: ' . ($end_time - $start_time) . '<br>';

并得到以下结果:

Curl without handle reuse: 8.5690529346466
Curl with handle reuse: 5.3703031539917

因此,在多次连接到同一服务器时,重用相同的句柄实际上可以显著提高性能。我尝试连接到不同的服务器:

$url_arr = array(
    'http://www.google.com/',
    'http://www.bing.com/',
    'http://www.yahoo.com/',
    'http://www.slashdot.org/',
    'http://www.stackoverflow.com/',
    'http://github.com/',
    'http://www.harvard.edu/',
    'http://www.gamefaqs.com/',
    'http://www.mangaupdates.com/',
    'http://www.cnn.com/'
);
ob_start(); //Trying to avoid setting as many curl options as possible
$start_time = microtime(true);
foreach ($url_arr as $url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_exec($ch);
    curl_close($ch);
}
$end_time = microtime(true);
ob_end_clean();
echo 'Curl without handle reuse: ' . ($end_time - $start_time) . '<br>';

ob_start(); //Trying to avoid setting as many curl options as possible
$start_time = microtime(true);
$ch = curl_init();
foreach ($url_arr as $url) {
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_exec($ch);
}
curl_close($ch);
$end_time = microtime(true);
ob_end_clean();
echo 'Curl with handle reuse: ' . ($end_time - $start_time) . '<br>';

并得到以下结果:

Curl without handle reuse: 3.7672290802002
Curl with handle reuse: 3.0146431922913

仍然有相当大的性能提升。


答案 2

推荐