A developer on my team mentioned that accessing an Object property via dot notation is faster than bracket notation. For example:
var sample = { name: 'First Name' }
var nameBracket = sample['name']
var namePeriod = sample.name
In this case, their belief was that the assignment of namePeriod
would be faster than nameBracket
.
Is this true? If so, why? If not, why not?
Related: How would one test this hypothesis or a similar question to determine JS function speed?
When you want to try to test speeds of different approaches, it seems the defacto tool is jsperf.com.
Someone has already questioned this, and created a test for it.
http://jsperf.com/dot-notation-vs-square-bracket-notation
The results seem to be about the same. What causes slowdows is when the contents of the bracket are a variable - at that point the compiler can no longer say to itself "Oh, ['foo'] is the same as .foo.. continuing on!".