PHP中curl扩展库和file_get_contents的区别与性能
一.性能
-
性能对比(只针对
GET
请求)次数 curl file_get_contents 执行1次 0.02s 0.02s 执行10次 9.06s 10.36s 执行100次 110.90s 117.18s 执行200次 212.46s 274.98s 执行500次 496.21s 584.18s -
性能对比代码
a.curl
的代码<?php function curl($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_exec($ch); curl_close($ch); } $url = 'http://www.baidu.com'; $a = microtime(true); $max = 100; for ($i = 0; $i < $max; $i++) { curl($url); } echo microtime(true) - $a;
b.
file_get_contents
的代码<?php $url = 'http://www.baidu.com'; $max = 100; $a = microtime(true); for ($i = 0; $i < $max; $i++) { file_get_contents($url); } echo microtime(true) - $a;
-
性能原因分析
-
单次耗时区别不大,由于次数越多,耗时差距越来越大
-
curl默认开启
CURLOPT_DNS_USE_GLOBAL_CACHE
一个全局的DNS缓存,减少耗时。但此选项非线程安全
-
二.功能区别
-
curl
扩展库使用系统curl功能。 -
file_get_contents
代码使用简单。 -
curl
可以模拟多种请求,例如:POST
数据,表单提交等,用户可以按照自己的需求来定制请求。而file_get_contents
只能使用get方式获取数据。 -
file_get_contents
函数会受到php.ini
文件中allow_url_open
选项配置的影响。如果该配置关闭了,则该函数也就失效了。而curl
不受该配置的影响。 -
file_get_contents
在请求HTTP时,使用的是http_fopen_wrapper
,不会keeplive
。而curl
却可以。这样在多次请求多个链接时,curl
效率会好一些。 -
file_get_contents
每次请求都会重新做DNS
查询,并不对DNS
信息进行缓存。但是CURL
会自动对DNS
信息进行缓存。对同一域名下的网页或者图片的请求只需要一次DNS
查询。