Are there any performance issues with passing an argument as an expression, instead of first making it a variable?
someFunction( x+2 );
vs.
var total = x+2;
someFunction( total );
And how about functions?
someFunction( someOtherFunction() );
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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:
The exact answer depends on the JavaScript engine’s implementation.
Most likely you won’t notice a performance difference.
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.