Does the JavaScript “in” operator execute a loop under the hood? [duplicate]

▼魔方 西西 提交于 2021-02-04 21:34:22

问题


I was studying some solutions to common algorithms and I ran across something that I am curious about. I tried to find the answer myself by googling and looking at some of the specifications but I am unable to find the answer to my question. The below algorithm basically checks to see if every item in the first array has a corresponding item squared in the second array. The naive solution (as they say) would have some sort of nested loop and be considered O(n2). The person who wrote the solution below said this is O(n).

I don't understand how this can be O(n) because he is using the Javascript "in" operator inside of his loop. As far as I can tell that operator checks to see if the value it's comparing exists in the object. How does it do that if it is not looping through the object under the hood? Is this really a linear time complexity?

function same(arr1, arr2) {

  if (arr1.length !== arr2.length) {
    return;
  }

  let frequencyMap1 = {};
  let frequencyMap2 = {};

  for (let val of arr1) {
    frequencyMap1[val] = (frequencyMap1[val] || 0) + 1;
  }

  for (let val of arr2) {
    frequencyMap2[val] = (frequencyMap2[val] || 0) + 1;
  }

  for (let key in frequencyMap1) {
    if (!(key ** 2 in frequencyMap2)) {
      return false;
    }

    if (frequencyMap2[key ** 2] !== frequencyMap1[key]) {
      return false
    }
  }

  return true;
}

console.log(same([1, 2, 3], [1, 4, 9])); // true

回答1:


Finding a key in an object is O(1). for .. in and just only in operator is different.

No matter how many keys are in an object, you can access it in constant time. Object or Map has a hash table to find a key.




回答2:


It depends. Lookup time on objects is not guaranteed by spec, so this could be O(n²) worst case. However most engines will represent objects as hashtables if you use a lot of different keys, and then the lookup time is O(1) and the algorithm runs at O(n).




回答3:


Different answers for in and for-in:

The in operator looks in an object (and if necessary, its prototype, and its prototype, etc.) to see if the object has a property with a given name. In any even half-decent JavaScript engine, that's not going to involve a loop other than the loop through the prototype chain (and on a good one, not even that, because on a good JavaScript engine objects get implemented as JIT classes so they know their structure).

for-in loops loop through the names of the enumerable properties in an object and its prototypes. So naturally, that involves a loop (possibly nested, given the prototype chain is involved).



来源:https://stackoverflow.com/questions/55078564/does-the-javascript-in-operator-execute-a-loop-under-the-hood

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!