计算字符串的实际长度,双字节字符(包括汉字在内)长度计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):

字符串长度matchreplace
50,000,00080518626
50,000,00093518019
50,000,000103847512
10,000,00016311783
10,000,00016461343
10,000,00016631372
5,000,000799728
5,000,000822806
5,000,000884645
1,000,000165128
1,000,000166143
1,000,000170113
500,0008458
500,0008354
500,0008661
100,000207
100,000185
100,000205
50,00011.793.01
50,00010.392.68
50,00011.992.82
10,0004.130.60
10,0004.320.59
10,0005.480.58
5,0001.880.31
5,0001.360.33
5,0002.710.31
1,0001.670.07
1,0000.210.07
1,0001.020.06
5000.08400.0322
5000.08200.0332
5000.08400.0320
1000.02290.0100
1000.04320.0149
1000.04710.0161

在大数据量情况下,replace性能初次会劣于match,多次执行后会优于match,小数据量情况下,replace性能优于match


点墨
26 声望3 粉丝

全栈前端开发工程师