What are the performance characteristics of JavaScript property access (on current implementations)?
If I use an object as a hash table (with string keys) can I safely assume O(1) or O(log n) access time?
Are there any common browsers or environments that are significantly faster/slower than the others and that I should keep an eye for?
Do the JavaScript standards have anything to say?
And most importantly:
Every object in JavaScript is implemented as an object hash, so there is no functional difference.
For example, check out this test:
var arr = [];
arr[5] = 5;
arr['5'] = 'not 5';
console.log(arr.length, arr);
// output: 6 [undefined, undefined, undefined, undefined, undefined, "not 5"]
Numbers are stringified when used as positions.
See Crockford's website about JavaScript for more information. The especially important part is under the heading "Arrays":
Arrays in JavaScript are also hashtable objects.
Performance isn't really an issue unless you have a ton of objects to keep track of (like 500,000+), in which case you're probably doing something wrong.
There are optimizations you can do, but they don't really make sense unless you're doing something unnatural with JavaScript (like compression algorithms... I worked on an LZMA implementation in JS... bad idea).
Note:
If you have a spare set (like you define only 10 indexes out of 10,000), you should probably be using a regular object. Arrays will initialize all 10,000 indexes to 'undefined', whereas Object.keys(obj)
will only report the 10 you have set. This is a minor optimization that actually makes sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With