/** 用于 一次性批量替换文本中多个匹配规则的字符
测试使用长度为1M的文本
**/
//1
Ext.Ajax.request({
url : 'data.json',
success : function (res) {
var t = res.responseText;
console.log(t.length);
var d = (new Date).getTime();
t = t.replace(/\./g, 'A').replace(/\;/g, 'B').replace(/\-/g, 'C').replace(/\,/g, 'D');
var d1 = (new Date).getTime();
console.log(d1 - d);
});
// output: 997920 757
//2
Ext.Ajax.request({
url : 'data.json',
success : function (res) {
var t = res.responseText;
console.log(t.length);
var d = (new Date).getTime();
var o = {};
o['.'] = 'A';
o[';'] = 'B';
o['-'] = 'C';
o[','] = 'D';
var reg = (function () {
var a = [];
for (var p in o) {
a.push(p);
}
return RegExp(a.join('|'));
})();
t = t.replace(reg, function (match, s) {
return o[match];
});
var d1 = (new Date).getTime();
console.log(d1 - d);
}
});
// output : 997920 229
本文通过两个不同方法对比了在1M大小文本中进行批量字符替换的效率。方法一使用了连续的replace调用;而方法二则创建了一个映射对象,并通过正则表达式进行替换。测试结果显示方法二比方法一稍快。
1万+

被折叠的 条评论
为什么被折叠?



