紀錄一下幾個 javascript 清空陣列的方法比較。

  • 指派一個新的空陣列 reference
    arr = [];
    ps. 如果有其他變數仍然指到原本的陣列,會造成占較多 memory,以至於效能不佳。
  • 長度設為 0
    arr.length = 0;
  • splice 移除
    arr.splice(0, arr.length);
  • 迴圈 pop 清空
    while (arr.length > 0) {
    arr.pop();
    }
    
  • 迴圈 shift 清空
    while (arr.length > 0) {
    arr.shift();
    }
    

來看看上面這幾個清空陣列的 jsperf 效能比較:https://jsperf.com/array-destroy/40

在多數瀏覽器,popshift 的方法最有效率,但在 firefox new 的方法效率遠大於其他方法。

 

參考資料:

http://www.jstips.co/en/javascript/two-ways-to-empty-an-array/

Leave a Reply