背景
當我們需要進行一些鍵值對數據的存儲時,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 *