Lately I was spinning fine in a project about response times, and I had the doubt of knowing what is the fastest way to access the attributes of an Object in javascript, at the moment I only know 2:
Defined a simple object:
let obj = { nombre: 'juan pirulo' };
There are 2 ways to access an attribute of it, either to read or modify:
obj.nombre
either
obj['nombre']
The question is which of these 2 forms is the fastest in large numbers of calls or the difference is negligible.
The two syntaxes have exactly the same performance because at execution level they are identical: They access the member of the corresponding object.
In JavaScript there are no static members, all members of an object are dynamic, so in both cases it is a question of accessing the corresponding member within the object's property set.
The real difference is that the bracket syntax allows using any
string
as a key while the.
only notation allows valid identifiers .Example:
As a recommendation, I would tell you to always use the notation
.
as long as possible, and leave the bracket notation for when the name of the member to access is known at runtime (it is dynamic)Example
Do the test:
You will notice that the time difference varies and is quite subtle. Sometimes one is faster than the other and vice versa.
If you build blocks of 10 iterations for each one; you will notice that the result is the same:
You will notice that for each case, the first 2 attempts are considerably slower. Then, the other values are kept relatively constant ( They are already in cache ). If you consider the values constant for both cases, the result will be the same. Sometimes one is faster than the other and sometimes not.
My advice, don't pay attention to performance for this kind of cases. Both ways are fast enough to affect performance in any noticeable way.