PHP: is JSON or XML parser faster? PHP: is JSON or XML parser faster? xml xml

PHP: is JSON or XML parser faster?


The comment from Adam above convinced me to benchmark it. Using https://twitter.com/status/mentions.[format], I found that simplexml_load_string() is SLIGHTLY faster than json_decode(). But the difference is practically a margin of error.

Test #1 time (xml): 3.75221395493 secondsTest #2 time (xml): 4.1562371254 secondsTest #3 time (xml): 3.60420489311 secondsTest #4 time (xml): 3.85622000694 secondsTest #5 time (xml): 3.89622211456 seconds

versus

Test #1 time (json): 4.53225803375 secondsTest #2 time (json): 4.06823205948 secondsTest #3 time (json): 4.03222990036 secondsTest #4 time (json): 3.80421590805 secondsTest #5 time (json): 3.88022208214 seconds

on the following code (where I've already curl'ed the data to a file, data.[xml,json]).

<?php$test = 'json';  //xml or json$data = implode(file("data.".$test),"\r\n");for ($t=1; $t<=5; $t++) {    $start[$t] = microtime(1);    for ($i=0; $i<3000; $i++) {        if ($test == 'xml') $xml = simplexml_load_string($data);        else $json = json_decode($data);    }    $end[$t] = microtime(1);    echo "<p>Test #{$t} time ({$test}): " . ($end[$t] - $start[$t]). " seconds</p>";}


I didn't do any benchmark but...

Since JSON is only a description of nested string sequences, without the need to offer a DOM interface, attributes parsing and other subtle stuff, my guess is that a JSON parser is WAY faster that an XML parser.


I tend to find that simplexml_load_string() is faster than json_decode() when the json return is an object.

However, having the json returned as an array using json_decode($string, true) is actually a lot faster than using an object (as is true with most things PHP when comparing arrays to objects).

Ive seen json_decode() being over twice as fast as simplexml_load_string() under these circumstances.