JavaScript计算字符串实际字节长度:match与replace方法性能对比

作者:巡夜人

时间:2026-10-30

浏览:145

本文介绍JavaScript中计算字符串实际字节长度的两种常用方法:利用match遍历判断和replace替换统计。通过对比双字节字符(如汉字)与ASCII字符的处理逻辑,并展示5000万数据量级下的性能测试代码及结果,分析match与replace在不同数据规模下的执行效率差异,为开发者提供选型参考。

文章目录

测算文本的真实字节数

非ASCII字符(含中文)按2字节计算,ASCII字符按1字节计算

方案一:利用正则匹配

export function getByteLenMatch(data) {
  let result = 0;
  for (let s of data) {
    result += s.match(/[^\\x00-\\xff]/ig) == null ? 1 : 2;
  }
  return result;
}

方案二:利用字符串替换

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");
    }

耗时对比(毫秒)

字符串长度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,持续运行后反超;数据量小时,replace更快

以上内容为JS获取字符串真实长度示例详情,更多JS字符串长度相关教程请参阅本站其他文章!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章