我们在使用AJAX来做服务器端和客户端交互的时候,一般的做法是让服务器端返回一段JSON字符串,然后在客户端把它解析成JavaScript对象。
解析时用到的方法一般是eval或者new function,而目前IE8和Firefox3.1又内置了原生的JSON对象(据说会有一定的性能提升)。那我们在实际使用的时候怎样从这三种方法(因为性能问题,不考虑用javascript实现的解析)里面来选择呢?面对众多的浏览器,哪种方式的性能是最好的呢?
var count = 10000,
o = null,
i = 0,
jsonString = '{"value":{"items": [{"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}]},"error":null}';
eval 解析
代码如下:
var beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = eval( "(" + jsonString + ")" );
}
Console.output( "eval:" + ( new Date() - beginTime ) );
new Function 函数解析
代码如下:
var beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = new Function( "return " + jsonString )();
}
Console.output( "new Function:" + ( new Date() - beginTime ) );
native 原生解析
代码如下:
if ( typeof JSON !== "undefined" ) {
var beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = JSON.parse( jsonString ); }
Console.output( "native:" + ( new Date() - beginTime ) );
} else {
Console.output( "native:not support!" );
}
1、Firefox2、3全部垫底,IE6的性能优于IE7(可能和机器不一致有关),Chrome和Safari4的性能远远超出其它浏览器。
2、不同的浏览器下eval和new Function的性能不一致,总的来说eval更好,但Firefox下new Function的性能是eval的一倍,为了更好的兼容各个浏览器,我们把对JSON的解析单独封装成一个对象来处理:
wrapper
var __json = null;
if (typeof JSON !== "undefined") {
__json = JSON;
}
var browser = Browser;
var JSON = {
parse: function(text) {
if (__json !== null) {
return __json.parse(text);
}
if (browser.gecko) {
return new Function("return " + text)();
}
return eval("(" + text + ")")
}
};
var beginTime = new Date();
for (i = 0; i < count; i++) {
o = JSON.parse(jsonString);
}
Console.output("wrapper:" + (new Date() - beginTime));
主要修改的代码:
//eval 2: var beginTime = new Date();
for (i = 0; i < count; i++) {
o = eval("(" + '{"value":{"items": [{"x":' + i + ',"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}]},"error":null}' + ")");
}
Console.output("eval:" + (new Date() - beginTime));
//new Function
beginTime = new Date();
for (i = 0; i < count; i++) {
o = new Function("return " + '{"value":{"items": [{"x":' + i + ',"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}]},"error":null}')();
}
Console.output("new Function:" + (new Date() - beginTime));
//native
if (typeof JSON !== "undefined") {
beginTime = new Date();
for (i = 0; i < count; i++) {
o = JSON.parse('{"value":{"items": [{"x":' + i + ',"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}]},"error":null}');
}
Console.output("native:" + (new Date() - beginTime));
} else {
Console.output("native:not support!");
}
//wrapper
var __json = null;
if (typeof JSON !== "undefined") {
__json = JSON;
}
var browser = Browser;
var JSON = {
parse: function(text) {
if (__json !== null) {
return __json.parse(text);
}
if (browser.gecko) {
return new Function("return " + text)();
}
return eval("(" + text + ")")
}
};
beginTime = new Date();
for (i = 0; i < count; i++) {
o = JSON.parse('{"value":{"items": [{"x":' + i + ',"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}]},"error":null}');
}
Console.output("wrapper:" + (new Date() - beginTime));
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Parse JsonString</title>
</head>
<body>
<div id="consoleRegion"></div>
<script type="text/javascript">
//yui
var Browser = function() {
var o = {
ie: 0,
opera: 0,
gecko: 0,
webkit: 0
};
var ua = navigator.userAgent, m;
if ( ( /KHTML/ ).test( ua ) ) {
o.webkit = 1;
}
// Modern WebKit browsers are at least X-Grade
m = ua.match(/AppleWebKit\/([^\s]*)/);
if (m&&m[1]) {
o.webkit=parseFloat(m[1]);
}
if (!o.webkit) { // not webkit
// @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr)
m=ua.match(/Opera[\s\/]([^\s]*)/);
if (m&&m[1]) {
o.opera=parseFloat(m[1]);
} else { // not opera or webkit
m=ua.match(/MSIE\s([^;]*)/);
if (m&&m[1]) {
o.ie=parseFloat(m[1]);
} else { // not opera, webkit, or ie
m=ua.match(/Gecko\/([^\s]*)/);
if (m) {
o.gecko=1; // Gecko detected, look for revision
m=ua.match(/rv:([^\s\)]*)/);
if (m&&m[1]) {
o.gecko=parseFloat(m[1]);
}
}
}
}
}
return o;
}();
var Console = {
consoleRegion: null,
getRegion: function() {
if ( this.consoleRegion === null ) {
this.consoleRegion = document.getElementById( "consoleRegion" );
}
return this.consoleRegion;
},
output: function( text ) {
this.getRegion().innerHTML += "<br/>" + text;
}
};
//test code
var count = 10000, o = null, i = 0, jsonString = '{"value":{"items": [{"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}]},"error":null}';
//eval
var beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = eval( "(" + jsonString + ")" );
}
Console.output( "eval:" + ( new Date() - beginTime ) );
//new Function
beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = new Function( "return " + jsonString )();
}
Console.output( "new Function:" + ( new Date() - beginTime ) );
//native
if ( typeof JSON !== "undefined" ) {
beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = JSON.parse( jsonString );
}
Console.output( "native:" + ( new Date() - beginTime ) );
} else {
Console.output( "native:not support!" );
}
//wrapper
var __json = null;
if ( typeof JSON !== "undefined" ) {
__json = JSON;
}
var browser = Browser;
var JSON = {
parse: function( text ) {
if ( __json !== null ) {
return __json.parse( text );
}
if ( browser.gecko ) {
return new Function( "return " + text )();
}
return eval( "(" + text + ")" )
}
};
beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = JSON.parse( jsonString );
}
Console.output( "wrapper:" + ( new Date() - beginTime ) );
//alert( o.value.items[0].z );
</script>
</body>
</html>
package com.ghj.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
public class JsonServlet extends HttpServlet {
private static final long serialVersionUID = -699926309344319475L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/json;charset=utf-8");
PrintWriter out = response.getWriter();
Map<String, List<String>> dataMap = new HashMap<String, List<String>>();
List<String > gradeList = new ArrayList<String>();//年级
gradeList.add("初中一年级");
gradeList.add("初中二年级");
gradeList.add("初中三年级");
dataMap.put("gradeList", gradeList);
List<String> courseList = new ArrayList<String>();//课程
courseList.add("语文");
courseList.add("数学");
courseList.add("物理");
dataMap.put("courseList", courseList);
out.write(new Gson().toJson(dataMap));
out.flush();
out.close();
}
}
说明:这里使用了gson-2.2.2.jar包<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>首页</title>
<script type="text/javascript" src="<%=basePath%>js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
$("#json").click(function(){
$.ajax({
type: "POST",
url: "<%=basePath%>JsonServlet",
success: function(data){
var grades = data.gradeList;
for(var index in grades){//年级
console.log(grades[index]);
}
var courses = data.courseList;
for(var index in courses){//课程
console.log(courses[index]);
}
},
error:function(){
alert("数据请求失败!");
}
});
});
});
</script>
</head>
<body>
<button id="json">JavaScript解析JSON字符串</button>
</body>
</html>