phetsims/gravity-and-orbits

Style question: bracket notation vs dot notation

Closed this issue · 5 comments

In gravity and orbits code, I am seeing several instances that use the bracket notation for property access:

model[currentObj + 'Position'] = model[currentObj + 'Position'].timesScalar( 1.0 / scale ).plus( model[currentObj + 'Velocity'].timesScalar( dt ).plus( model[currentObj + 'Acceleration'].timesScalar( dt * dt / 2.0 ) ) ).timesScalar( scale );

instead of the dot notation, here is the above rewritten with dot notation:

body.position = body.position.timesScalar( 1.0 / scale ).plus( body.velocity ).timesScalar( dt ).plus( body.acceleration ).timesScalar( dt * dt / 2 ).timesScalar( scale );

The latter (dot notation) is more consistent with the style we use throughout the rest of our code base, and it seems to me a bit easier to read. Is there a good reason to use the bracket notation? Should the sim be converted to use dot notation?

It looks performance characteristics are about the same on many platforms, with a notable speed improvement on Safari: http://jsperf.com/dot-notation-vs-bracket-notation/2

This amount of speed increase for safari may be in the noise compared to more expensive steps like drawing.

The most upvoted answer in Stack Overflow's "JavaScript property access: dot notation vs. brackets?" question concludes:

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

http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets

I agree that dot notation is more readable, so I would like to see us standardize on it and only use bracket notation when it is necessary to do so.

Your jsperf didn't include the string concatenations (and thus JIT dynamic lookups that in the jsperf can be compiled to static references) that are going in in the above code. I think the dot notation will be faster in that specific case, and I prefer the dot notation style.

+1 for dot notation. I especially don't like the style of bracket notation that uses string concatenation.