简体   繁体   English

为什么在JavaScript中要实现哈希表,ES6映射通常比普通对象快?

[英]Why is it in JavaScript, to implement a hash table, ES6 map is generally faster than plain objects?

I've been grinding LeetCode these days using JavaScript. 这些天来,我一直在使用JavaScript来开发LeetCode。 I found that if I need to implement a hash table, for example this famous question, https://leetcode.com/problems/two-sum/ , using a ES6 map generally results in better speed compared to plain old javascript object, like 20ms faster. 我发现如果我需要实现一个哈希表(例如,这个著名的问题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;
  }
};

To me that the biggest use case for ES6 Map over plain old objects is when we want the keys not only to be strings. 对我来说,在普通旧对象上使用ES6 Map的最大用例是当我们希望键不仅是字符串时。 Can someone please explain to me why Map is superior in terms of speed and what are some other use cases where Map is better than plain old objects in JavaScript 有人可以向我解释为什么Map在速度方面优越,还有其他一些用例,其中Map比JavaScript中的普通旧对象更好

In your example, the Map version uses numbers for keys, while the object version uses strings. 在您的示例中, Map版本使用数字作为键,而object版本使用字符串。

Converting all those numbers (like target-value ) into strings probably accounts for most of the extra cost in the object version. 将所有这些数字(如target-value )转换为字符串可能会占object版本中大部分额外费用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM