Json字串轉換為JS對象的高效方法執行個體

來源:互聯網
上載者:User

今天學習JQuery源碼看到一下方法,原來還可以這樣解析JSON字串:
複製代碼 代碼如下:
  parseJSON: function( data ) {
  if ( typeof data !== "string" || !data ) {
   return null;
  }

  // Make sure leading/trailing whitespace is removed (IE can't handle it)
  data = jQuery.trim( data );

  // Make sure the incoming data is actual JSON
  // Logic borrowed from http://json.org/json2.js
  if ( /^[/],:{}/s]*$/.test(data.replace(///(?:["////bfnrt]|u[0-9a-fA-F]{4})/g, "@")
   .replace(/"[^"///n/r]*"|true|false|null|-?/d+(?:/./d*)?(?:[eE][+/-]?/d+)?/g, "]")
   .replace(/(?:^|:|,)(?:/s*/[)+/g, "")) ) {

   // Try to use the native JSON parser first
   return window.JSON && window.JSON.parse ?
    window.JSON.parse( data ) :
    (new Function("return " + data))();

  } else {
   jQuery.error( "Invalid JSON: " + data );
  }
 }

這個方法核心的代碼就是:
複製代碼 代碼如下:
(new Function("return " + data))();

它使用了Function()建構函式。講json字串作為函數執行資料傳入,定義後立即執行該函數,此時這個函數會返回JSON對象

我做了一個測試,用這個方法解析JSON字串的效率要比用Eval解析快好幾百倍
複製代碼 代碼如下:
var jsonStr ="{";
for(var i=0;i<10000;i++){
 jsonStr+="a"+i+":"+i+","
}
jsonStr = jsonStr.substring(0,jsonStr.length-1);
jsonStr+="}";

var date = new Date();
var start = date.getTime()
//var boj = (new Function("return "+jsonStr ))();
var boj = eval("("+jsonStr+")");
var date1 = new Date();
console.info(date1.getTime()-start);

我用firfox測試結果,用eval解析花費了7234毫秒,而用函數這種方法,用了55毫秒,太神奇了.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.