计算字符串的理论长度,双字节字符(包含汉字在内)长度计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

作者:点墨
版权:本文版权归作者所有
转载:欢送转载,但未经作者批准,必须保留此段申明;必须在文章中给出原文连贯;否则必究法律责任