Which is better:
int sum = a b;
std::cout << sum;
std::cout << a b;
In terms of performance and efficiency?
CodePudding user response:
Is it better two add two numbers to a new variable
No, it's not better in general.
or adding them together while displaying?
No, it's not better in general.
Either is usually fine. The intermediate local variable has advantages such as ability to give an understandable name, and it reduces the complexity of individual expressions. But adding a variable increases the total number of names which is another form of complexity. It's a matter of finding a good balance, and the "bestness" is subjective.
In terms of performance and efficiency?
Not using a local variable is pretty much never more efficient than using a variable. But there is no difference in the shown example. Furthermore, there is no difference in most simple cases.
The difference - if any - is primarily in readability.
Consider another example where you use the result of the operation multiple times. In that case, it would be rare for a program that repeats an operation to be more efficient than another program that stores the result in a variable. But there's still no difference if the case is simple.
CodePudding user response:
It actually depends on what you are trying to measure, either efficiency or speed or maybe to track variables and their values in memory. If you will want to re-use that variable later within your codebase then it will not better over-riding although you can have access to speed with your code logic. For speed and efficiency, overriding variable values will increase memory efficiency as you will not be using a lot of memory spaces for a single code you are writing. Is better to read best practices for a Programming language especially if you are thinking of moving into production.