Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the big O for JavaScript's array when used as a hash?

What's the big O for JavaScript's array access when used as a hash?

For example,

var x= [];
for(var i=0; i<100000; i++){
   x[i.toString()+'a'] = 123; // using string to illustrate x[alpha]
}
alert(x['9999a']); // linear search?

One can hope JS engines will not use a linear search internally O(n), but is this for sure?

like image 622
Alex Nolasco Avatar asked Oct 04 '10 19:10

Alex Nolasco


1 Answers

Accessing object properties and array elements in JavaScript is syntacticly assumed to be done in constant time: O(1). Performance characteristics are not guaranteed in the ECMAScript specification, but all the modern JavaScript engines retrieve object properties in constant time.

Here's a simple example showing how access times grow when the container is x1000 times bigger:

var largeObject = {};
var smallObject = {};

var x, i;

for (i = 0; i < 1000000; i++) {
   largeObject['a' + i] = i;
}

for (i = 0; i < 1000; i++) {
   smallObject['b' + i] = i;
}

console.time('10k Accesses from largeObject');
for (i = 0; i < 10000; i++) x = largeObject['a' + (i % 1000000)];
console.timeEnd('10k Accesses from largeObject');

console.time('10k Accesses from smallObject');
for (i = 0; i < 10000; i++) x = largeObject['a' + (i % 1000)];
console.timeEnd('10k Accesses from smallObject');

Results in Firebug, Firefox 3.6.10 (Mac OS X 10.6.4 - 2.93Ghz Intel Core 2 Duo):

10k Accesses from largeObject: 22ms
10k Accesses from smallObject: 19ms

Results in Chrome Dev Tools 6.0.472:

10k Accesses from largeObject: 15ms
10k Accesses from smallObject: 15ms

Internet Explorer 8.0.7600 with Firebug Lite on Windows 7

10k Accesses from largeObject: 250ms
10k Accesses from smallObject: 219ms
like image 54
Daniel Vassallo Avatar answered Oct 06 '22 00:10

Daniel Vassallo