关于javascript:JavaScript计算字符串实际长度

6次阅读

共计 1224 个字符,预计需要花费 4 分钟才能阅读完成。

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

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

正文完
 0