lolmoney
lolmoney

Reputation: 21

Optimizing cURL for speed

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 time 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?

Upvotes: 1

Views: 17730

Answers (7)

Arjun J Gowda
Arjun J Gowda

Reputation: 730

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.

Upvotes: 3

KsaR
KsaR

Reputation: 601

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:

  1. Remove the $url variable and paste the string in file_get_contents().
  2. If $params is not changed, then you can also remove http_build_query(); and save its result to the variable by one time.

Upvotes: 0

mixdev
mixdev

Reputation: 2844

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.

Upvotes: 10

MattB
MattB

Reputation: 724

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.

Upvotes: 6

RusAlex
RusAlex

Reputation: 8585

you can use multi threading for launching more copies of your script. it can be faster perform your requests

Upvotes: -1

simshaun
simshaun

Reputation: 21476

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.

Upvotes: 4

Tyler Eaves
Tyler Eaves

Reputation: 13133

The one thing you could maybe do is look at using keepalive connections if the requests are to the same server.

Upvotes: 0

Related Questions