Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript performance consideration. Is dot operator faster than subscript notation?

Is dot operator faster than subscript notation?

var obj = {x: '5'};
obj.x = 'some value';
obj['x'] = 'some value';
like image 646
Mike Avatar asked Sep 03 '11 08:09

Mike


People also ask

Is it more efficient to access properties via dot or square bracket notation?

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.

Which object property access notation is slightly faster than other?

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.

What does dot notation do in Javascript?

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.

Why do we use bracket notation?

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.


2 Answers

Not anything incredibly worrying. Acessing variables by window or eval are significantly slower though.

http://jsperf.com/dot-vs-square-bracket/5

like image 198
Lime Avatar answered Nov 15 '22 14:11

Lime


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.

like image 28
Arc Avatar answered Nov 15 '22 13:11

Arc