1

I am currently trying to speed optimise the fetching of the data via the remote API.

I am using it in this way:

$response = wp_remote_get('https://some-api.com/endpoint');
$response_body = wp_remote_retrieve_body($response);
$data = json_decode($response_body, true);

It returns an array of data, that I am traversing and saving to appropriate variables with which I later insert the data where I want it to be inserted.

All of this is done via AJAX, so that the data is being inserted dynamically.

The whole thing takes around 400-600ms. But if I try to access the api endpoint directly with pasting the API URL in the URL bar in my browser it just takes around 50ms. Does the json_decode & saving and outputting from variables account to the other 400-500ms? Is there any other way that I could minimase the impact of loading time?

3

The most performant way of fetching remote API data is not fetching it at all. Thus, use Transients API or WP Object Cache to save your computed results for future use and avoid calling external API (and further computations) on every subsequent request. Additionally, fetching, invalidating and regeneration of this data can be done in the background, but that's more of an advanced technique and will heavily depend on your current architecture and specific use case.

The 50ms vs 500ms difference comes from:

  • connecting to your own ajax endpoint
  • loading and executing part of WordPress engine
  • connecting, sending the request to external API endpoint and getting the response back (that 50ms, more or less)
  • parsing the response
  • your custom computational logic

Most time is spent on the first 3 steps, not the last 2. You can profile your code to see the full picture.

1
  • Thanks :) I have chose to use Transients API, since they provide the functionality I need. So no more requests to the 3rd party API when each user clicks on that specific page instead it looks up for the saved Transient :)
    – Jernej
    Mar 2 '18 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.