In the world of browser performance you can find yourself looking for the little things to make big differences, or even a lot of little things to make a bigger difference together. I’ve been researching one particular change that is coming down the pike: native JSON handling. John Resig wrote about the need for native JSON support in the browser in 2007 and its finally come. The difference it makes between Firefox 3.0 and 3.5 is major, the difference between Internet Explorer 7 and 8 is important, and the safety that native support brings for prevention of cross site scripting (XSS) is critical.
I’ve created two tests that you can try for yourself: the eval test and the JSON test. The tests loop 20 times to give you a broader test range and reveal the average time. There are notes in the test pages to clarify a few observations, but I’ll put them here just for the sake of a single source. The test pulls in 1600 JSON objects and either evaluates them using the JavaScript eval function (eval(/*JSON String*/);), or it parses them with the native JSON parser (JSON.parse(/*JSON String*/)). For consistency’s sake I used the data from John Resig’s test which I have copied onto my server to reduce the load on his server and not steal bandwidth. My tests were run locally to reduce bandwidth latency influencing results, but you can see that over the Internet, even on a broadband connection, the performance only gets worse.
Firefox 3.5 has javascript tracing enabled and the typical test results will show a much slower first pass with subsequent results being much, much faster. It should never be assumed that the user will be getting the exact same data back like this test shows, so the slower performance should be expected.
Internet Explorer 8’s Eval test appears to be almost as fast as the JSON test and their eval code’s execution is pretty fast already. However, the JSON.parse() code appears to be much safer to use and is thus preferable.
The final results are based on the averages (which are much more consistent than comparing the ‘best’ numbers): eval is roughly 500 milliseconds (or 500%) slower in Firefox 3.5 the first time and nearly the same speed in Internet Explorer 8 with an average of 10 seconds slower in 20 passes. So for either identical or much faster performance and greater safety against XSS it is a no-brainer to switch to including native JSON support as a preferred method of dealing with JSON data over eval.
I do want to note that I was impressed by Internet Explorer 8’s eval speed, it was much greater than I had expected, and generally disappointed with Firefox’s, but since it is an evil function to use, that’s not all bad.