优化小写JSON属性名称的JavaScript代码 [英] Optimizing JavaScript code that lowercases JSON property names
问题描述
我在一个Web应用程序上工作,该应用程序接收带有大写属性名称的JSON数据.我需要这些属性名称为小写,因此我正在使用一个函数来递归遍历JSON对象并将其转换为小写.
I working on a web application that receives JSON data with uppercase property names. I need those property names to be lowercase, so I'm using a function to loop recursively through the JSON object and convert them to lowercase.
问题是我的JSON回复可能很大.我希望该功能执行良好,即使它必须处理具有60,000个属性名称和各种嵌套级别的JSON.
The problem is my JSON replies can get very large. I want the function to perform well even if it has to process JSON with 60,000 property names and various levels of nesting.
小写的功能是:
FN = function (obj)
{var ret = null;
if (typeof(obj) == "string" || typeof(obj) == "number")
return obj;
else if (obj.push)
ret = [];
else
ret = {};
for (var key in obj)
ret[String(key).toLowerCase()] = FN(obj[key]);
return ret;
};
我正在这里进行一些基准测试: http://jsfiddle.net/emw89/7/
And I'm performing some benchmarking here: http://jsfiddle.net/emw89/7/
以上测试在我的计算机上大约在570ms处计时.
The above test clocks in at ~570ms on my machine.
我有什么办法可以改善此功能的性能?
Is there anything I can do to improve the performance of this function?
我关闭了IE,重新打开IE,然后再次运行jsfiddle基准测试-现在对我来说大约是180ms.直到那时我的IE已经连续开放了几天,所以也许这就是造成如此糟糕的性能的原因.无论哪种方式,我仍然对是否有进一步优化此功能的方法感兴趣.任何花费额外时间处理JSON的时间都会直接增加每个AJAX请求的耗时.
I closed my IE, re-opened IE and ran the jsfiddle benchmark again--it's now coming in at ~180ms for me. My IE had been open for a couple days straight until just then, so maybe that's what was causing such poor performance. Either way, I'm still interested if there's a way to optimize this function further. Any time extra time spent processing JSON directly adds to the elapsed time of every AJAX request.
推荐答案
var lowerCache = {};
FN = function (obj)
{
if (typeof(obj) === "string" || typeof(obj) === "number")
return obj;
var l = obj.length;
if (l) {
l |= 0;
var result = [];
result.length = l;
for (var i = 0; i < l; i++) {
var newVal = obj[i];
result[i] = typeof(newVal) === "string" ? newVal : FN(newVal);
}
return result;
} else {
var ret = {};
for (var key in obj) {
var keyStr = typeof(key) === "string" ? key : String(key);
var newKey = lowerCache[keyStr];
if (newKey === undefined) {
newKey = keyStr.toLowerCase();
lowerCache[keyStr] = newKey;
}
var newVal = obj[key];
ret[newKey] = typeof(newVal) === "string" ? newVal : FN(newVal);
}
return ret;
}
};
快100%.
这篇关于优化小写JSON属性名称的JavaScript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!