map | object | |
插入性能 | 高 | 低 |
删除性能 | 高 | 低 |
查找速度 | 快 | 慢 |
内存占用 | 少 | 多 |
插入性能
简单测一测, 如果哪些地方不对请大佬指正
针对数值,浮点数,字符串,symbol类型为键的双方插入性能测试
const mapTest = (key) => {
const map = new Map()
const start = +new Date()
for (let i = 0; i < 5000000; i++) {
map.set(key, i)
}
const end = +new Date()
return end - start
}
const objTest = (key) => {
const obj = new Object()
const start = +new Date()
for (let i = 0; i < 5000000; i++) {
obj[key] = i
}
const end = +new Date()
return end - start
}
console.log('map', '数值:', mapTest(Math.floor(Math.random() * 1000000)), '浮点值:', mapTest(Math.random() * 10), '字符串:', mapTest(Math.random().toString()), 'symbol:', mapTest(Symbol(Math.random())));
console.log('obj', '数值:', objTest(Math.floor(Math.random() * 1000000)), '浮点值:', objTest(Math.random() * 10), '字符串:', objTest(Math.random().toString()), 'symbol:', objTest(Symbol(Math.random())));
浏览器输出结果 :
总结:
涉及大量插入数据时map占优
删除性能
针对数值,浮点数,字符串,symbol类型为键的双方删除性能测试
const mapTest = (key) => {
const map = new Map()
for (let i = 0; i < 5000000; i++) {
map.set(key, i)
}
const start = +new Date()
for (let i = 0; i < 5000000; i++) {
map.delete(key)
}
const end = +new Date()
return `${end - start}毫秒`
}
const objTest = (key) => {
const obj = new Object()
for (let i = 0; i < 5000000; i++) {
obj[key] = i
}
const start = +new Date()
for (let i = 0; i < 5000000; i++) {
delete obj[key]
}
const end = +new Date()
return `${end - start}毫秒`
}
console.log('map删除性能测试5000000条数据', '数值:', mapTest(Math.floor(Math.random() * 1000000)), '浮点值:', mapTest(Math.random() * 10), '字符串:', mapTest(Math.random().toString()), 'symbol:', mapTest(Symbol(Math.random())));
console.log('obj删除性能测试5000000条数据', '数值:', objTest(Math.floor(Math.random() * 1000000)), '浮点值:', objTest(Math.random() * 10), '字符串:', objTest(Math.random().toString()), 'symbol:', objTest(Symbol(Math.random())));
浏览器输出结果:
总结:
涉及大量删除数据时map占优
查找速度
针对数值,浮点数,字符串,symbol类型为键的双方查找key性能测试
const mapTest = (key) => {
const map = new Map()
for (let i = 0; i < 5000000; i++) {
map.set(key, i)
}
const start = +new Date()
for (let i = 0; i < 5000000; i++) {
map.has(key)
}
const end = +new Date()
return `${end - start}毫秒`
}
const objTest = (key) => {
const obj = new Object()
for (let i = 0; i < 5000000; i++) {
obj[key] = i
}
const start = +new Date()
for (let i = 0; i < 5000000; i++) {
obj.hasOwnProperty(key)
}
const end = +new Date()
return `${end - start}毫秒`
}
console.log('map查找性能测试5000000条数据查找不同的key: ', '数值:', mapTest(Math.floor(Math.random() * 1000000)), '浮点值:', mapTest(Math.random() * 10), '字符串:', mapTest(Math.random().toString()), 'symbol:', mapTest(Symbol(Math.random())));
console.log('obj查找性能测试5000000条数据查找不同的key: ', '数值:', objTest(Math.floor(Math.random() * 1000000)), '浮点值:', objTest(Math.random() * 10), '字符串:', objTest(Math.random().toString()), 'symbol:', objTest(Symbol(Math.random())));
浏览器输出结果:
内存占用
对象占用的空间是Map的1.5倍左右