Does declaring a variable cost an overhead?

Viewed 460

My lead always asks me to get rid of the new variables as much as I can saying it costs an overhead. However, I'm not sure if that actually degrades the performance. If anything, making new variables improves the readability of my code. Does it actually worsen the performance?

Option 1:

var a = something1();
var b = something2();
var c = something3();
var d = something4(a, b, c);

option 2: Making it just one line of code.

var d = something4(something1(), something2(), something3());

Please note: at times, it gets complicated and the readability worsens.

3 Answers

In the strictest sense, yes a variable uses resources (memory or processing). But that alone doesn't mean it's bad or wasteful. Use a variable to make your code more readable and/or to store data that will be needed to be reused.

Later, when it's time to QA your work you can worry about optimization. And there is a very well-known mantra in software development that trying to optimize your code as you initially write it often leads to more problems than it solves.

But I have to say that if having something in a variable is causing your performance to suffer, you've got other problems to worry about.

If you use variable once, get rid of it. If 2+ times - declare variable. Variable can be declared in this case only if too many executions make debug tricky. Therefore if action fits in line - it is better to use option 2

No change in performance. Just readability that also can be affected by too big amount of variables.

Both options are almost the same for the performance. With the option 2 all function calls are evaluating to a hidden internal memory space which is bound to the function parameters. This is almost an equivalent to assigning vars in option 1.

Related