html如何统计字母出现的次数,优化这个用于统计字母出现次数的函数,看看你优化后的函数需要耗时几毫秒?...

做优化最好基于同样的样本,'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));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值