# JavaScript - Map vs Object ###### tags: `Javascript` ==比較Map與Object 操作上效能差異== ### 建置100萬筆資料 ```javascript= const standard = BigInt(1000000); const testmap = new Map() const obj = {} const setMap = process.hrtime.bigint(); for (let i = 0; i < 1000000; i++){ testmap.set(`key${i}`,`test ${i}`); } const EndsetMap = process.hrtime.bigint(); const setObj = process.hrtime.bigint(); for (let i = 0; i < 1000000; i++){ obj[`key${i}`] = `test ${i}`; } const endsetObj = process.hrtime.bigint(); ``` ![](https://i.imgur.com/MUzZYKv.png) >Map **寫入資料**,優於Object --- ### 連續取得單筆資料(10萬筆) ```javascript= const getMap = process.hrtime.bigint(); const value = testmap.get(`key1000`); const endgetMap = process.hrtime.bigint(); const getObj = process.hrtime.bigint(); const value2 = obj[`key1000`] const endgetObj = process.hrtime.bigint(); ``` ![](https://i.imgur.com/7WPCdy0.png) > Object **取得單筆資料**,優於Map --- ### 轉換成Array(100萬筆) ```javascript= const MapLoopStart = process.hrtime.bigint(); const data = [...testmap.keys()]; const MapLoopEND = process.hrtime.bigint(); const ArrayStart = process.hrtime.bigint(); const data2 = Array.from(testmap.keys()); const ArrayEND = process.hrtime.bigint(); const ObjLoopStart = process.hrtime.bigint(); const data3 = Object.keys(obj) const ObjLoopEND = process.hrtime.bigint(); ``` ![](https://i.imgur.com/2z3vtl0.png) >Map **轉換到一般Array**,優於Object(==明顯!!==) ### 結論 > * 在單筆查詢速度, Object 略優於 Map > > * 在操作上Array提供許多方便的函式,時常會將Object轉換為Array進行操作 > 轉換成Array的過程, Map本身是可疊代的,效能上明顯優於Object, > 當需要儲存大量key-value pair資料操作時, Map是相當不錯的選擇!!