Is dot operator faster than subscript notation?
var obj = {x: '5'};
obj.x = 'some value';
obj['x'] = 'some value';
Key DifferencesDot notation is faster to write and easier to read than bracket notation. However, you can use variables with bracket notation, but not with dot notation.
Dot notation is faster to write and clearer to read. Square bracket notation allows access to properties containing special characters and selection of properties using variables.
Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property. Example: var cat = { name: 'Moo', age: 5, }; console.
We must use bracket notation whenever we are accessing an object's property using a variable or when the property's key is a number or includes a symbol or is two words with a space.
Not anything incredibly worrying. Acessing variables by window
or eval
are significantly slower though.
http://jsperf.com/dot-vs-square-bracket/5
This is maybe outdated information, but it is a statement affecting at least older Safari versions. From O'Reilly's Writing Efficient JavaScript:
For most browsers, there is virtually no difference between using dot notation for object property access (data.count) and bracket notation (data["count"]). The one exception is Safari, where bracket notation is significantly slower than dot notation. This holds true even for Safari 4 and later using the Nitro JavaScript engine.
Looks like http://jsperf.com/ has been taken down -- it says Website Disabled
, but using an embedded WebKit engine from Qt4 it looks like that this statement is true, using this test:
var t = new Date().getTime();
var x = { c: 123 };
for (var i = 0; i < 5000000; i++)
x['c'] += 2;
document.write(( new Date().getTime() - t ) + '; value ' + x.c);
var t = new Date().getTime();
var x = { c: 123 };
for (var i = 0; i < 5000000; i++)
x.c += 2;
document.write(( new Date().getTime() - t ) + '; value ' + x.c);
Using x['c']
took about 4 seconds while x.c
ran for about 3 seconds.
Current Firefox and Chrome appear to make no distinction between the two.
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