Javascript: Running time of search through Object?

回眸只為那壹抹淺笑 提交于 2019-12-24 15:54:28

问题


I have a JavaScript Object as:
object1 = { "abc" : "def", "ghi" : "jkl" }

Now, when I write object1["abc"]. Is this search a linear time search, i.e., O(n) or constant time search, i.e., O(1)?


回答1:


Accessing an array/object in Javascript is an O(1) operation.




回答2:


Well, I've made a simple program testing this, and it doesn't show constant access time. Most likely there are some other things involved - optimization or memory management or something, but it clearly shows dependence on amount of attributes.

For object with 10 attributes, it takes around 160 ms to do the 100 million accesses, for object with 100k attributes, it takes around 650 ms (on my PC with Chrome). So it doesn't look constant at all, but it is true, that for "normal" amounts of attributes it will not probably matter.

JS:

function go(amount) {
  var object1 = {};
  for (var i = 0; i < amount; i++) {
    object1['id' + i] = i;
  }

  var start = new Date().getTime();
  var j = 0;
  for (var i = 0; i < 100000000; i++) {
    j += object1['id3'];
  }
  var end = new Date().getTime();
  console.log(j);
  document.getElementById('result').innerHTML = end - start;
}

HTML:

<button onclick="go(10);">Run with 10 attributes</button>
<button onclick="go(100000);">Run with 100 000 attributes</button>
<br>
The result is <span id="result">0</span> ms

Here is the link of Fiddle



来源:https://stackoverflow.com/questions/21385144/javascript-running-time-of-search-through-object

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