Javascript: Running Time Of Search Through Object?
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 s
Solution 1:
Accessing an array/object in Javascript is an O(1) operation.
Solution 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
Post a Comment for "Javascript: Running Time Of Search Through Object?"