I'm starting to develop a web application in PHP that I hope will become incredibly popular and make me famous and rich. :-)
If that time comes, my decision whether to parse the API's data as XML with SimpleXML or to use json_decode could make a difference in the app's scalability.
Does anyone know which of these approaches is more efficient for the server?
Update: I ran a rudimentary test to see which method was more performant. It appears that json_decode
is slightly faster executing than simplexml_load_string
. This isn't terribly conclusive because it doesn't test things like the scalability of concurrent processes. My conclusion is that I will go with SimpleXML for the time being because of its support for XPath expressions.
<?php
$xml = file_get_contents('sample.xml');
$json = file_get_contents('sample.js');
$iters = 1000;
// simplexml_load_string
$start_xml = microtime(true);
for ($i = 0; $i < $iters; ++$i) {
$obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
}
$end_xml = microtime(true);
// json_decode
$start_json = microtime(true);
for ($i = 0; $i < $iters; ++$i) {
$obj = json_decode($json);
}
$end_json = microtime(true);
?>
<pre>XML elapsed: <?=sprintf('%.4f', ($end_xml - $start_xml))?></pre>
<pre>JSON elapsed: <?=sprintf('%.4f', ($end_json - $start_json))?></pre>
Result:
XML elapsed: 9.9836
JSON elapsed: 8.3606
As the "lighter" format, I'd expect JSON to be slightly less stressful on the server, but I doubt it will be the biggest performance issue you find yourself dealing with as your site grows in popularity. Use whichever format you're more comfortable with.
Alternatively, if you know how you'll be structuring your data, you could try making an XML-formatted version and a JSON-formatted version and just run it against your setup a few hundred thousand times to see if it makes a noticeable difference.
There's only one way to determine which is going to be easier on your server in your application with your data.
Test it!
I'd generate some data that looks similar to what you'll be translating and use one of the unit testing frameworks to decode it a few thousand times using each of SimpleXML and json_decode, enough to get meaningful results. And then you can tell us what worked.
Sorry this isn't exactly the sort of answer you were looking for, but in reality, it's the only right way to do it. Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With