We parse a JSON string to JSON object when we handle response of server in AJAX.We use eval or new Function to parse JSON string normally, and IE8 and Firefox3.1 has a native JSON support( Native JSON parsing is much faster).How can we choose from the three methods in practice? And how can we know whose performance is the best since there are so many browers?
Code & Concern
defined a json string and circle numbersparse json string and record time
- new Function
It includes IE6, 7 , 8; Firefox2, 3, 3.1; Chrome; Opera and Safari3, 4.
T9300 CPU + 4G RAM + Windows2003, IE8 in Vista, IE7 in another machine( 2G CPU + 2G RAM + Windows2003 )
*The smaller the number is,the better the result will be.
*The column in green shows the best performance, while in red shows the worst.
Firefox2, 3 gain the worst performance, IE6 better than IE7( may be related with machines ), Chrome and Safari4 are far superior to other browsers.
Genally speaking, eval is better than new Function,though they have different results in different browsers. But the "new Function" is the double performance of eval in Firefox, so we wrap a class to parse json string to gain better performance in cross-browser.
The results with wrapper:
After wrapping, it is slower than before due to the cost, but it offers a guarantee to call better implementation.
We should choose a different method when using different browsers:
- choose eval in IE6, 7
- choose native JSON in IE8
- choose new Function in Firefox2, 3
- choose eval in Safari4
- eval has the same performance as new Function on the whole when you use the other browsers.
Hope this helps,
- 2009.03.23: Disabled all Firefox' Add-Ons
someone told me got a different result after he ran the code in Firefox, I doubt Firefox’s Add-Ons conduces to wrong result, so I run it after I disabled Firebug.
We made a mistake in tests about Firefox, but it is not good enough to our without Firebug.
- 2009.03.31: Use different Json strings in the loops
according to Oliver' reply, modify code:
opera is best performance, but Ie8 is better than chrome and safari.