55

I'm creating a sophisticated JavaScript library for working with my company's server side framework.

The server side framework encodes its data to a simple XML format. There's no fancy namespacing or anything like that.

Ideally I'd like to parse all of the data in the browser as JSON. However, if I do this I need to rewrite some of the server side code to also spit out JSON. This is a pain because we have public APIs that I can't easily change.

What I'm really concerned about here is performance in the browser of parsing JSON versus XML. Is there really a big difference to be concerned about? Or should I exclusively go for JSON? Does anyone have any experience or benchmarks in the performance difference between the two?

I realize that most modern web developers would probably opt for JSON and I can see why. However, I really am just interested in performance. If there's a proven massive difference then I'm prepared to spend the extra effort in generating JSON server side for the client.

geme_hendrix
  • 917
  • 1
  • 7
  • 9

11 Answers11

32

JSON should be faster since it's JS Object Notation, which means it can be recognized natively by JavaScript. In PHP on the GET side of things, I will often do something like this:

<script type="text/javascript">
    var data = <?php json_encode($data)?>;
</script>

For more information on this, see here:

Why is Everyone Choosing JSON Over XML for jQuery?

Also...what "extra effort" do you really have to put into "generating" JSON? Surely you can't be saying that you'll be manually building the JSON string? Almost every modern server-side language has libraries that convert native variables into JSON strings. For example, PHP's core json_encode function converts an associative array like this:

$data = array('test'=>'val', 'foo'=>'bar');

into

{"test": "val", "foo": "bar"}

Which is simply a JavaScript object (since there are no associative arrays (strictly speaking) in JS).

Community
  • 1
  • 1
treeface
  • 13,270
  • 4
  • 51
  • 57
  • 9
    Also, (as pointed out in the linked question), JSON is generally more lightweight simply in terms of bytes, making it more efficient to transmit. Most likely, you'll get much more of a performance benefit from reducing your bandwidth requirements than any difference in parsing JSON vs. XML. – Chris Lawlor Jan 04 '11 at 17:29
  • 1
    I believe json_encode/decode need to be enabled when PHP is compiled. – Alexander Jan 04 '11 at 17:49
  • @Alexander: I've never had to do that before. It always just works. – treeface Jan 04 '11 at 17:52
  • 2
    Correction, by adding --disable-json when compiling, JSON can be disabled. – Alexander Jan 04 '11 at 18:04
  • 2
    This answer is probably wrong on a few counts. JS does have associative arrays, in fact both {} and [] are associative arrays TMK. Second, the fact that JSON is a notation similar to JS objects doesn't mean that a JS implementation of JSON parsing is faster than a Java implementation of JSON parsing, etc. –  Dec 23 '18 at 22:07
19

Firstly, I'd like to say thanks to everyone who's answered my question. I REALLY appreciate all of your responses.

In regards to this question, I've conducted some further research by running some benchmarks. The parsing happens in the browser. IE 8 is the only browser that doesn't have a native JSON parser. The XML is the same data as the JSON version.

Chrome (version 8.0.552.224), JSON: 92ms, XML: 90ms

Firefox (version 3.6.13), JSON: 65ms, XML: 129ms

IE (version 8.0.6001.18702), JSON: 172ms, XML: 125ms

Interestingly, Chrome seems to have almost the same speed. Please note, this is parsing a lot of data. With little snippets of data, this isn't probably such a big deal.

geme_hendrix
  • 917
  • 1
  • 7
  • 9
  • 5
    I would be very interested to see an update of this with Firefox 9+ and Chrome 16+ – Dave Jan 23 '12 at 18:05
  • 1
    Strange results, from my own experience json was alwyas much, much faster in browsers. Maybe you have some specific data, where the xml overhead is not much compared to the data itself. But, if it works that way for you, then it must be true. You can never assume something, you should always test. – bartosz.r Nov 14 '12 at 21:19
  • I don't think that these benchmarks are accurate. As @justkt shared at his answer; [this link](http://www.navioo.com/ajax/ajax_json_xml_Benchmarking.php) has a good comparison between them. – scaryguy Dec 08 '15 at 09:14
  • In fact I think these benchmarks are good. I followed the link that @scaryguy shared and then I tested myself (http://www.navioo.com/ajax/examples/json/test.php). Both in Chrome and in IE there was minimal difference between JSON and XML. – Dušan Mar 02 '17 at 14:23
9

Benchmarks have been done. Here's one. The difference in some of the earlier browsers appeared to be an entire order of magnitude (on the order of 10s of milliseconds instead of 100s of ms), but not massive. Part of this is in server response time - XML is bulkier as a data format. Part of it is parsing time - JSON lets you send JavaScript objects, while XML requires parsing a document.

You could consider adding to your public API a method to return JSON instead of modifying existing functions if it becomes and issue, unless you don't want to expose the JSON.

See also the SO question When to prefer JSON over XML?

Community
  • 1
  • 1
justkt
  • 14,610
  • 8
  • 42
  • 62
  • 2
    Minor nitpick, wrt "JSON lets you send JavaScript objects, while XML requires parsing a document" -- this is not quite true; both need to be written and read (serialize/deserialize, marshal/unmarshal), as all data is sent as byte stream. It is true however that data structure being built for JSON is more natural, compared to XML DOM trees. – StaxMan Jan 04 '11 at 18:10
  • @StaxMan - thanks for the correction. The technical answer I meant to imply was that JSON on the client side can be `eval`-ed to an object (with the usual caveats of eval applying), while the DOM tree for XML must be parsed. – justkt Jan 04 '11 at 18:11
  • @justkt Ah ok, yes, then it would be related to binding of data itself – StaxMan Jan 04 '11 at 18:18
  • 1
    @quertymk, They also have JavaScript support, and therefor, JSON parsers. – Alexander Jan 04 '11 at 19:21
  • All the major browsers now have support for [native JSON](http://en.wikipedia.org/wiki/JSON#Native_JSON), which is more secure, and often faster, than `eval` – Matthew Flaschen Jan 06 '11 at 08:50
  • @justkt - note that the "bulkier" part is essentially nullified if you use mod_deflate (gzipping) your responses. Further, for a public RESTapi, use max-age cache headers and public caching headers and you don't even need to worry about server side time, since they'll be cached for common calls. :) – Joseph Lust Jul 18 '12 at 19:59
  • I just ran the benchmark and JSON vs XML was even in the first, and JSON:XML speed was 3:2 in the second. I'm in IE 8. Reason? – AncientSwordRage Sep 20 '12 at 16:29
4

Performance isn't really a consideration, assuming that you're not talking about gigabytes of XML. Yes, it will take longer (XML is more verbose), but it's not going to be something that the user will notice.

The real issue, in my opinion, is support for XML within JavaScript. E4X is nice, but it isn't supported by Microsoft. So you'll need to use a third-party library (such as JQuery) to parse the XML.

Anon
  • 2,654
  • 16
  • 10
  • 2
    Wasn't me, but one thing I would point out is that XML parsing can already be done by AJAX request; resulting xml can be accessed directly as DOM tree. Or perhaps you were thinking of data binding from DOM (which is tree built from parsed xml) to "real" Javascript objects? – StaxMan Jan 04 '11 at 18:11
2

If possible, it would make sense to just measure it. By 'if possible' I mean that tooling for javascript (esp. for performance analysis) may not be quite as good as for stand-alone programming languages.

Why measure? Because speculation based solely on properties of data formats is not very useful for performance analysis -- developers' intuitions are notoriously poor at predicting performance. In this case it just means that it all comes down to maturity of respective XML and JSON parser (and generators) in use. XML has the benefit of having been around longer; JSON is bit simpler to process. This based on having actually written libraries for processing both. In the end, if all things are equal (maturity and performance optimization of libraries), JSON can indeed be bit faster to process. But both can be very fast; or very slow with bad implementations.

However: I suspect that you should not worry all that much about performance, like many have already suggested. Both xml and json can be parsed efficiently, and with modern browsers, probably are. Chances are that if you have performance problems it is not with reading or writing of data but something else; and first step would be actually figuring out what the actual problem is.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
1

It also depends on how your JSON is structured. Tree-like structures tend to parse more efficiently than a list of objects. This is where one's fundamental understanding of data structures will be handy. I would not be surprised if you parse a list-like structure in JSON that might look like this:

{
        {
            "name": "New York",
            "country":"USA",
            "lon": -73.948753,
            "lat": 40.712784
        },
        {
            "name": "Chicago",
            "country":"USA",
            "lon": -23.948753,
            "lat": 20.712784
        },
        {
            "name": "London",
            "country":"UK",
            "lon": -13.948753,
            "lat": 10.712784
        }
}

and then compare it to a tree like structure in XML that might look like this:

<cities>
  <country name="USA">
     <city name="New York">
        <long>-73.948753</long>
        <lat>40.712784</lat>
     </city>
     <city name="Chicago">
        <long>-23.948753</long>
        <lat>20.712784</lat>
     </city>
  </country>
 <country name="UK">
     <city name="London">
        <long>-13.948753</long>
        <lat>10.712784</lat>
     </city>
  </country>
</cities>

The XML structure may yield a faster time than that of JSON since if I loop through the node of UK to find London, I don't have to loop through the rest of the countries to find my city. In the JSON example, I just might if London is near the bottom of the list. But, what we have here is a difference in structure. I would be surprised to find that XML is faster in either case or in a case where the structures are exactly the same.

Here is an experiment I did using Python - I know the question is looking at this strictly from a JavaScript perspective, but you might find it useful. The results show that JSON is faster than XML. However, the point is: how you structure is going to have an effect on how efficiently you are able to retrieve it.

Mr. Concolato
  • 2,224
  • 5
  • 24
  • 44
1

since JSON is native in and designed FOR Javascript, it's going to out-perform XML parsing all day long. you didn't mention your server-side language, in PHP there is the json_encode/json_decode functionality built into the PHP core...

FatherStorm
  • 7,133
  • 1
  • 21
  • 27
1

the difference in performace will be so tiny, you wouldn't even notice it (and: you shouldn't think about performance problems until you have performance problems - there are a lot of more important points to care for - maintainable, readable and documented code...).

but, to answer ayou question: JSON will be faster to parse (because it's simple javascript object notation).

oezi
  • 51,017
  • 10
  • 98
  • 115
  • 2
    That difference is only with small amounts of data. If your parsing more than a couple dozen lines (or so), then there will definitely be a significant amount of time spent parsing the data. – Alexander Jan 04 '11 at 17:43
1

In this situation, I'd say stick with the XML. All major browsers have a DOM parsing interface that will parse well-formed XML. This link shows a way to use the DOMParser interface in Webkit/Opera/Firefox, as well as the ActiveX DOM Object in IE: https://sites.google.com/a/van-steenbeek.net/archive/explorer_domparser_parsefromstring

Alex Vidal
  • 4,080
  • 20
  • 23
  • 3
    All browsers (with proper JavaScript support) are able to parse well-formed JSON code just as well as XML. – Alexander Jan 04 '11 at 17:40
  • 1
    @Alexander: For sure. I wasn't implying that they didn't, just that he stated that switching to JSON on the server-side is a non-trivial task due to API interfaces and such, so I recommended sticking with XML instead. – Alex Vidal Jan 04 '11 at 17:58
  • @Alex Vidal, While I would normally agree, if he / she is planning on writing for XML-based code, it might just be better to convert over to JSON now so more code doesn't need to be re-written. – Alexander Jan 04 '11 at 19:17
  • 1
    @Alex: I don't think JSON encoding should be considered non-trivial. In fact, most languages (or libraries, if there is no native support) make it entirely trivial to convert native data types into JSON. – treeface Jan 04 '11 at 19:19
  • @treeface: I agree that the actual conversion is non-trivial in most cases, I was referring specifically to his/her scenario "However, if I do this I need to rewrite some of the server side code to also spit out JSON. This is a pain because we have public APIs that I can't easily change." If the output is already XML, and it's well-formed, and it's a pain to convert it to also output JSON, then XML is the best choice. – Alex Vidal Jan 04 '11 at 19:23
  • @Alex: You're right...I suppose it entirely depends on the data source. I'm just so used to working with output from databases that constructing XML out of native data types always seems much more of a chore than something like: `die(json_encode($query->result_array());` (not that I would ever mix my controller and model actions ;-) – treeface Jan 04 '11 at 19:25
0

Another reason to stick with XML is, that if you switch to JSON, you modify the "maintenance contract". XML is more typed than JSON is, in the sense that it works more naturally with typed languages (i.e. NOT javascript).

If you change to JSON, some future maintainer of the code base might introduce a JSON array at some point which has mixed type content (e.g. [ "Hello", 42, false ]), which will present a problem to any code written in a typed language.

Yes, you could do that as well in XML but it requires extra effort, while in JSON it can just slip in.

And while it does not seem like a big deal at first glance, it actually is as it forces the code in the typed language to stick with a JSON tree instead of deserializing to a native type.

BitTickler
  • 10,905
  • 5
  • 32
  • 53
-2

best example i have found about these two is :

http://www.utilities-online.info/xmltojson/#.VVGOlfCYK7M

that means JSON is more human readable and understandable than XML.

hitesh141
  • 963
  • 12
  • 25