做优化最好基于同样的样本,'http://www.sina.com.cn/'的返回值是动态的,会有一定的误差,特别是这个计算的结果受长度影响很大。
思路上优化了两个小的地方,一个是遍历的时候以固定的顺序用charCodeAt访问大字符串(html),这样理论上会更好的利用缓存;其次是避免使用toLowerCase,因为这个方法会对非ASCII字符做很多判断,如果只需要处理字母的话,自己用char code会更快。
为了追求更好的结果,手动初始化了_c。
在我电脑上的测试结果:
ms: 8.922ms
{ a: 26176,
b: 6757,
c: 14595,
d: 10290,
e: 19355,
f: 6699,
g: 6052,
h: 9973,
i: 19716,
j: 1620,
k: 5125,
l: 16049,
m: 8369,
n: 17727,
o: 12164,
p: 8366,
q: 535,
r: 13128,
s: 18335,
t: 22595,
u: 5905,
v: 4130,
w: 4053,
x: 2014,
y: 3396,
z: 581 }
const fetch = require('isomorphic-fetch')
function charStat(url) {
return fetch(url)
.then(response => response.text())
.then(html => {
console.time('ms')
const _c = {
97: 0,
98: 0,
99: 0,
100: 0,
101: 0,
102: 0,
103: 0,
104: 0,
105: 0,
106: 0,
107: 0,
108: 0,
109: 0,
110: 0,
111: 0,
112: 0,
113: 0,
114: 0,
115: 0,
116: 0,
117: 0,
118: 0,
119: 0,
120: 0,
121: 0,
122: 0,
};
let i;
const length = html.length;
for (i = 0; i < length; i++) {
const charCode = html.charCodeAt(i);
if (charCode > 96 && charCode < 123) {
_c[charCode]++;
} else if (charCode > 64 && charCode < 91) {
const lowerCharCode = charCode + 32;
_c[lowerCharCode]++;
}
}
const transformedCounter = {};
for (const key in _c) {
transformedCounter[String.fromCodePoint(key)] = _c[key];
}
console.timeEnd('ms')
return transformedCounter
})
}
charStat('http://www.sina.com.cn/').then(result => console.log(result));