Which one of these two is more ‘efficient’:
for (int i = 0; i < 10; i++) {
int x = i * 2;
}
or –
int x;
for (int i = 0; i < 10; i++) {
x = i * 2;
}
(Just an example)
I understand they are different in essence – so please do not address the difference in their use.
In a case where both would prove to do the same thing – will creating the x variable multiple times be a less efficient method rather than just creating it once and simply reassigning its value?
No, in this case, with the way compilers are, there is no performance difference.
I prefer the first approach from a readability point of view, but that’s something to be discussed elsewhere.
However, as a bonus section to this answer:
In the above case, this will be a performance issue since the
calculateUserCountFromDatabaseOrSomething()method is going to be called on every iteration of the loop. This is something that definitely needs to be considered when writing software.