Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kevin Korte
28,149 PointsFastester of two language options to parse a large JSON string?
So I'm building a wordpress site and am using a weather API to have complete control of the look and information that is show.
I first started by parsing the JSON with PHP and although it's working, I've noticed it single handily slowed down my web page. When I remove the code my site loads fast again.
I tried parsing the same JSON with Javascript, and it seems to load it much faster.
Is this normal? Is it something I could have done? Or should I just go ahead and plug away and set up everything with JS from the JSON.
1 Answer
Andrew Whitfield
5,239 PointsI think you meant "Faster" in the subject and "handedly" instead of "handily".
To test which is faster, store the response from the weather API into a file and read it locally with PHP instead of fetching it from the API. Compare that speed with JSON. Being in the browser can mask the actual wait time. Being on the server, the first thing you see isn't sent until your request is returned.
With PHP, you're sending the request to the server, first. Then, it sends a request to the API and waits for a response. The API returns the JSON to PHP, which then parses it and prepares the output. Then, you get output.
All that time, you're waiting for a response.
If you move the code to JS, you start seeing page content much sooner and while it's loading, JS can usually begin requesting the API contents. This gives you the appearance of getting your content more quickly. To test it, you'll have to time each step carefully and then compare.
I think that you should do what suits your use case. If, for example, you can cache the data returned in the JSON response, then it will probably be faster to render it into the page at the same time you make the page request. If you can't or it's not appropriate to, then if the user experience is improved by doing it in JS (and you have no reason to do this in PHP), then by all means do it that way.
I think you have to decide if you need that data or not and if you need to comply with any accessibility requirements for your target audience before making the final decision.