JavaScript计算字符串实际长度方法示例
作者:点墨
这篇文章主要为大家介绍了JavaScript计算字符串实际长度方法示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
计算字符串的实际长度
双字节字符(包括汉字在内)长度计2,ASCII字符计1
方法1:使用match
export function getByteLenMatch(data) {
  let result = 0;
  for (let s of data) {
    result += s.match(/[^\\x00-\\xff]/ig) == null ? 1 : 2;
  }
  return result;
}方法2:使用replace
export function getByteLenReplace(data) {
  return data.replace(/[^\\x00-\\xff]/ig, "aa").length;
}测试代码:
let testData = new Array(50000000).fill("哈").toString();
    for (let i = 0; i < 3; i++) {
      console.time("getByteLenMatch");
      getByteLenMatch(testData);
      console.timeEnd("getByteLenMatch");
      console.time("getByteLenReplace");
      getByteLenReplace(testData);
      console.timeEnd("getByteLenReplace");
    }性能比较(单位ms)
| 字符串长度 | match | replace | 
|---|---|---|
| 50,000,000 | 8051 | 8626 | 
| 50,000,000 | 9351 | 8019 | 
| 50,000,000 | 10384 | 7512 | 
| 10,000,000 | 1631 | 1783 | 
| 10,000,000 | 1646 | 1343 | 
| 10,000,000 | 1663 | 1372 | 
| 5,000,000 | 799 | 728 | 
| 5,000,000 | 822 | 806 | 
| 5,000,000 | 884 | 645 | 
| 1,000,000 | 165 | 128 | 
| 1,000,000 | 166 | 143 | 
| 1,000,000 | 170 | 113 | 
| 500,000 | 84 | 58 | 
| 500,000 | 83 | 54 | 
| 500,000 | 86 | 61 | 
| 100,000 | 20 | 7 | 
| 100,000 | 18 | 5 | 
| 100,000 | 20 | 5 | 
| 50,000 | 11.79 | 3.01 | 
| 50,000 | 10.39 | 2.68 | 
| 50,000 | 11.99 | 2.82 | 
| 10,000 | 4.13 | 0.60 | 
| 10,000 | 4.32 | 0.59 | 
| 10,000 | 5.48 | 0.58 | 
| 5,000 | 1.88 | 0.31 | 
| 5,000 | 1.36 | 0.33 | 
| 5,000 | 2.71 | 0.31 | 
| 1,000 | 1.67 | 0.07 | 
| 1,000 | 0.21 | 0.07 | 
| 1,000 | 1.02 | 0.06 | 
| 500 | 0.0840 | 0.0322 | 
| 500 | 0.0820 | 0.0332 | 
| 500 | 0.0840 | 0.0320 | 
| 100 | 0.0229 | 0.0100 | 
| 100 | 0.0432 | 0.0149 | 
| 100 | 0.0471 | 0.0161 | 
在大数据量情况下,replace性能初次会劣于match,多次执行后会优于match,小数据量情况下,replace性能优于match
以上就是JavaScript计算字符串实际长度方法示例的详细内容,更多关于JavaScript计算字符串长度的资料请关注脚本之家其它相关文章!
