javascriptv8spidermonkeychakra

Is this JavaScript optimization or not?


Can someone explain me what are the differences between those two functions below?

I'm wondering if JavaScript engines do some kind of nano-optimizations here.

function withoutVar() {                                                                                                                   
  return 'stackoverflow';                                                                                                                    
}
function withVar() {
  var result = 'stackoverflow';
  return result;
}
var a = withoutVar();
var b = withVar();  

Solution

  • The difference is that your function withVar causes the implementation to access the underlaying Activation Object respectively Lexical Environment Record. So technically, this function will run slower, but we are not even talking about micro optimizations, more like nano optimizations.

    Some browsers might indeed optimize that code into the direct return statement for withVar. Webkit or at least Chrome with their V8 engine are good candidates for that. Either way, again, this is entirely trivial and you should not be concerned about run-time performance here.

    JSPerf benchmark

    Difference on my machine (Chrome) is about 0.32% on ~7.000.000 calls.


    The only argument I would consider to buy on stuff like this is, that the former function works with less characters. In that way, you can optimize your filesize and reduce traffic over the wire (but even then, we would have to optimize such statements on many instances before it really comes into play)