I have recently begun using more getter functions as opposed to direct access to make my code more flexible. I am curious what the cost of this is in terms of speed. Suppose
You don't need to create redundant getters/setters functions like this in JavaScript. If you at a later stage require some validation when setting a property or some preparation when getting a property you can do this.
var star = {
get planet() {
this._planet.prepare()
return this._planet
},
set planet(planet) {
if (! isPlanet(planet))
throw Error('Not a planet')
this._planet = planet
}
}
star.planet = earth
... and not alter the usage of the object.
In V8:
A function that is so short and doesn't have context allocated variables will get inlined. Unless of course too much inlining has already accumulated, in which case the call is still very cheap as the entire executing part of function fits in a 64 byte instruction cache line.
Context allocated variables happen when your function uses for example arguments
without being in strict mode or defines inner functions that reference the function's variables. Another problem is that on x64 functions cannot be inlined if the caller and callee cannot share the same context, so all in all, avoid closures like the plague.
See: http://jsperf.com/312319sakd although it looks like firefox uses dead code elimination (which is frustrating cos why waste time doing that?).
Bonus: this jsperf deliberately makes the getter function non-inlinable (through the huge comment which will make the function-size heuristic fail) in current V8. You can see that even if the function wasn't inlined, it's still only 25% slower than referencing the prop directly.
Note that when a function cannot be inlined it is considered a black box whose side effects are not known to the calling function, so the speed is highly context sensitive to the code.