JavaScript计算字符串实际字节长度:match与replace方法性能对比
作者:巡夜人时间:2026-10-30 23:17:22浏览:146
本文介绍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");
}耗时对比(毫秒)
| 字符串长度 | 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,持续运行后反超;数据量小时,replace更快
以上内容为JS获取字符串真实长度示例详情,更多JS字符串长度相关教程请参阅本站其他文章!
作者最新文章
怎么使用 JavaScript import() 实现模块的条件加载
2026-11-05 14:44:45
前端防御XSS攻击:怎么防止恶意JS注入与CSP策略配置
2026-11-04 08:51:38
怎么解决 Turf.js 处理大规模 GeoJSON 数据的性能瓶颈
2026-11-03 23:22:19
为什么不建议在JS中手动拼接JSON字符串?
2026-11-03 22:48:27
代码混淆对JS执行性能的影响测试与分析
2026-11-03 22:25:37
