[ javascript ] 數字類型轉換字符串性能測試 (benchmark)

1. 拉取依賴

yarn add benchmark 

2. 編寫測試用例 

const Benchmark = require('benchmark')
const suite = new Benchmark.Suite()

const a = 123456789

suite
  .add('String', () => {
    String(a)
  })
  .add('new String', () => {
    new String(a)
  })
  .add('template String', () => {
    ;`${a}`
  })
  .add("use +''", () => {
    '' + a
  })
  .on('cycle', e => {
    console.log(String(e.target))
  })
  .run({ async: true })

3. 結果

Ops/sec 測試結果以每秒鐘執行測試代碼的次數(Ops/sec)顯示,這個數值越大越好。

同時會顯示測試過程中的統計誤差,以及相對最好的慢了多少(%)

4. 結論

從結果看數字類型轉換字符串 使用''+Number 和 模板字符串 性能較好,new String() 性能最差。產生這樣結果的具體內部實現還有待考究。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章