I am making a web application that does API calls frequently. All API calls are just simple GET request, however I want to speed up loading ti开发者_如何学Pythonme and output return time up as much as possible. As of right now, I'm using cURL to do the API calls by using the following:
<?php
function api_call($params)
{
$base = 'https://api.example.com/Api?';
$url = $base . http_build_query( $params );
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
return json_decode($output,true);
}
?>
Is there any ways that I can optimize this for faster download and/or output time?
Is it possible to use IP address instead of the hostname api.example.com? If yes, you can speed up the namelookup_delay (a couple of hundred milliseconds in my case)
Keep-alive doesn't help in your case because keep-alives don't pool connections between requests. It is useful in the classic webbrowser-webserver scenario.
Is there any way you can use caching if data is sometimes the same between many API calls? It's more of a connection speed issue than a code issue.
Not really. The speed of the code can't really be optimized very much there. The bottleneck is going to be the connection between your server and their server. There is not very much you can do to speed that up in the code.
One more which you can do is Enable encoding also as it makes less data to be transferred.
curl_setopt($ch, CURLOPT_ENCODING, '');//set gzip, deflate or keep empty for server to detect and set supported encoding.
If you enable encoding then data would be compressed before it is sent. It might take some time to do it but very less data get transferred if you are working with large data.
The one thing you could maybe do is look at using keepalive connections if the requests are to the same server.
Optimized:
<?php
function api_call($params)
{
$url='https://api.example.com/Api?'.http_build_query($params);
return json_decode(file_get_contents($url),true);
}
?>
You can also:
- Remove the
$url
variable and paste the string infile_get_contents()
. - If
$params
is not changed, then you can also removehttp_build_query();
and save its result to the variable by one time.
you can use multi threading for launching more copies of your script. it can be faster perform your requests
精彩评论