[英]Why is it in JavaScript, to implement a hash table, ES6 map is generally faster than plain objects?
这些天来,我一直在使用JavaScript来开发LeetCode。 我发现如果我需要实现一个哈希表(例如,这个著名的问题https://leetcode.com/problems/two-sum/) ,则与普通的旧javascript对象相比,使用ES6 map
通常可以提高速度,例如快20毫秒。
var twoSum = function(nums, target) {
const map = new Map();
for (let [index, value] of nums.entries()) {
if (map.has(target - value)) return [map.get(target - value), index];
map.set(value, index);
}
};
var twoSum = function(nums, target) {
const map = {};
for (let [index, value] of nums.entries()) {
if (map[target - value] !== undefined) return [map[target - value], index];
map[value] = index;
}
};
对我来说,在普通旧对象上使用ES6 Map
的最大用例是当我们希望键不仅是字符串时。 有人可以向我解释为什么Map
在速度方面优越,还有其他一些用例,其中Map
比JavaScript中的普通旧对象更好
在您的示例中, Map
版本使用数字作为键,而object
版本使用字符串。
将所有这些数字(如target-value
)转换为字符串可能会占object
版本中大部分额外费用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.