Question

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();  
Was it helpful?

Solution 2

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)

OTHER TIPS

Some engines may perform such an optimisation. The Google Closure compiler certainly does so:

function withVar(){return"stackoverflow"}var a=withVar();

There will be virtually no difference in speed, but the "optimised" version is shorter (and therefore quicker for the client to download). Here's the results of a benchmark:

enter image description here

You can see that the "flat" version (without the variable declaration) is marginally faster (but look at the operations per second - this is an optimisation that's not even worth thinking about in terms of speed).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top