博客 / 詳情

返回

JavaScript計算字符串實際長度

計算字符串的實際長度,雙字節字符(包括漢字在內)長度計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

user avatar sunmengyuan 頭像 lankerens 頭像 jianqiangdepaobuxie 頭像 fulng 頭像 nian_5aedc008c1353 頭像 mrqueue 頭像 maogexiaodi 頭像 yexiaobai_616e2b70869ae 頭像 anetin 頭像 dingxi 頭像 rxliuli 頭像 thinkfault 頭像
15 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.