js中map和普通物件效能差距有多大?
阿新 • • 發佈:2020-09-03
背景
當我們需要進行一些鍵值對資料的儲存時,js 本身普通物件可以完成這個過程,es6 中提供了一個新的資料結構叫做 Map
二者之間效能差距有多大呢
普通物件
const map = {}; // insert key-value-pair map["key1"] = "value1"; map["key2"] = "value2"; map["key3"] = "value3"; // check if map contians key if (map.hasOwnProperty("key1")) { console.log("Map contains key1"); } // get value with specific key console.log(map["key1"]);
這種做法很常見,但同時也有很大的侷限
支援鍵型別
在 js 中,當你使用物件 object 時, 鍵 key 只能有 string 和 symbol 。然而 Map 的 key 支援的就比較多了,可以支援 string, symbol, number, function, object, 和 primitives
const map = new Map(); const myFunction = () => console.log("I am a useful function."); const myNumber = 666; const myObject = { name: "plainObjectValue", otherKey: "otherValue", }; map.set(myFunction, "function as a key"); map.set(myNumber, "number as a key"); map.set(myObject, "object as a key"); console.log(map.get(myFunction)); // function as a key console.log(map.get(myNumber)); // number as a key console.log(map.get(myObject)); // object as a key
封裝型別帶來的便利
- size map大小確定map只需要o(1),普通物件需要o(n)
const map = new Map(); map.set('someKey1', 1); map.set('someKey2', 1); ... map.set('someKey100', 1); console.log(map.size) // 100, Runtime: O(1) const plainObjMap = {}; plainObjMap['someKey1'] = 1; plainObjMap['someKey2'] = 1; ... plainObjMap['someKey100'] = 1; console.log(Object.keys(plainObjMap).length) // 100, Runtime: O(n)
- 增刪效能
map不需要把所有的鍵轉換為字串,節省了大量的效能 - 遍歷
const map = new Map();
map.set('someKey1', 1);
map.set('someKey2', 2);
map.set('someKey3', 3);
for (let [key, value] of map) {
console.log(`${key} = ${value}`);
}
// someKey1 = 1
// someKey2 = 2
// someKey3 = 3
const plainObjMap = {};
plainObjMap['someKey1'] = 1;
plainObjMap['someKey2'] = 2;
plainObjMap['someKey3'] = 3;
for (let key of Object.keys(plainObjMap)) {
const value = plainObjMap[key];
console.log(`${key} = ${value}`);
}
// someKey1 = 1
// someKey2 = 2
// someKey3 = 3
- 順序問題
物件中的key 是不保證順序的,因為對於 number 是存放到 elements 中,會按照從小到大,對於字串型別的是存放到 properties 中,會按照新增的順。
map 是保證順序的,按照新增的順序依次出來的。
- 原型鏈問題
普通物件繼承了很多原型方法,如toString
而map是乾淨的!
- 從 ECMAScript 2015 開始,如果你堅持使用原生的物件, 你可以 Object.create(null) 來生成一個乾淨的 object *