JSON vs XML parsing performance
Monday, October 1st, 2007In one project I worked on is using XML format to pass data and handle them inside HTML web page with a MSXML parser object. I was thought if I pass the data in JSON format directly could be faster. However, after I wrote a simple test code to verify the idea, I found I was wrong.
I believe it’s because XML parsing is inside MSXML object and JSON parsing is using Jscript engine which have more overhead.
<html>
<head>
<title>JSON vs XML parse performance in browser</title>
<script>function out(str)
{var o = document.getElementById("output");
if (o!=null)
o.innerHTML += str + "<br/>";}
function generateJSON(size)
{
var strJSON = "[";
ch = '';
for (i = 0 ; i < size; i++)
{
strJSON += ch + '{"filename":"file' + i + '.html"}';
ch = ',';
}
strJSON += ']‘;return strJSON;
}function generateXML(size)
{
var strXML = "<?xml version=’1.0′ encoding=’UTF-8′?>";strXML += "<files>";
for ( i = 0 ; i < size; i++)
strXML += "<file name=’file" + i + ".html’ ></file>";strXML += "</files>";
return strXML;
}function parseJSON(str)
{
data = eval(’(’ + str + ‘)’);
out(data.length + " data parsed");
}function parseXML(str)
{
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
xmlDoc.loadXML(str);if (xmlDoc.documentElement!=null)
{
var files = xmlDoc.documentElement.childNodes;
out(files.length + " data parsed");
}
else
{
out("Invalid XML parsed");
}
}function testJSON()
{
var datasize = document.getElementById("datasize").value;
out("generating JSON for test…");str = generateJSON(datasize);
out("begin parse JSON…");
var begin = new Date();
parseJSON(str);var end = new Date();
out("Parse JSON data with " + datasize + " records, used time: " + (end - begin) + "ms");}
function testXML()
{var datasize = document.getElementById("datasize").value;
out("generating XML for test…");
var strXML = generateXML(datasize);out("begin parse XML…");
var begin = new Date();
parseXML(strXML);var end = new Date();
out("Parse XML data with " + datasize + " records, used time: " + (end - begin) + "ms");}
</script>
<head><body>
Lines of data: <input type="edit" value="100" id="datasize"></input>
<input type="button" onclick="testJSON()" value="Test with JSON"></input>
<input type="button" onclick="testXML()" value="Test with XML"></input><hr/>
<div id="output">
</div>
</body>
</html>
Here is a result:
generating JSON for test…
begin parse JSON…
10000 data parsed
Parse JSON data with 10000 records, used time: 31ms
generating XML for test…
begin parse XML…
10000 data parsed
Parse XML data with 10000 records, used time: 16msgenerating JSON for test…
begin parse JSON…
20000 data parsed
Parse JSON data with 20000 records, used time: 78ms
generating XML for test…
begin parse XML…
20000 data parsed
Parse XML data with 20000 records, used time: 47ms
Feedback are welcome…
Popularity: 17% [?]
About