Variables vs Expressions as Javascript Arguments

Are there any performance issues with passing an argument as an expression, instead of first making it a variable?

someFunction( x+2 );


var total = x+2;
someFunction( total );

And how about functions?

someFunction( someOtherFunction() );


Though the difference is minimal, the answer is really implementation-specific; JavaScript engines almost certainly differ in how they allocate things. However, I can tell you that most likely, the differences are similar to what they would be in most other languages of which I can examine the memory and processor registers in the debugger. Let's examine one scenario:

var sum = x+2;

This allocates memory to hold sum, which hangs around as long as the function is in scope. If the function ends up being a closure, this could be forever. In a recursive function this could be significant.


In most languages, this will compute x+2 on the stack and pass the result to someFunction. No memory is left hanging around.

The answer would be exactly the same for a function return value.

So in summary:

  1. The exact answer depends on the JavaScript engine's implementation.

  2. Most likely you won't notice a performance difference.

  3. You may want to use variables when the result is re-used, or, when you want to examine the result easily in the debugger.

It's mostly a matter of personal preference.

No. And, more important, this sort of micro-optimization is (almost certainly) meaningless.

Having said that, if you were to use the result of the expression more than once, then there might be some completely imperceptible and totally not-worth-worrying-about benefit to saving the result of the calculation.

Write it to be readable. Don't worry about this stuff.

Just the obvious: Making a variable creates a variable. This costs memory and consumes some time when executing. Afterwards, it either will need time to garbage collect it, or not free the memory if your function leaks.

However, you won't notice any differences. The performance is not measurable at that level. Rule of thumb: Use variables when you really need them or when they improve readabilty of your code.

Need Your Help

Batch File to conditionally replace entire lines of a file

batch-file replace

I have a txt file with various lines or text. It is a config file, so each line is a new config setting.

How To Remove The Double Quotes From The Json data Result..?

jquery ajax json web-services cordova

I developing a windows phone 7 application using Phonegap. now I currently Working With The Web service Data Binding.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.