I have these two dummy codes (let them be written in both Java and C #, all variables are local):
Code 1:
int a; int b = 0; for (int i = 1; i < 10 ; i++) { a = 10; b += i;
Code 2:
int b = 0; for (int i = 1; i < 10 ; i++) { int a = 10; b += i;
At first glance, I would say that both codes consume the same amount of memory, but Code 1 is more efficient from the CPU point of view, since it creates and allocates the variable a only once. Then I read that garbage collectors are extremely efficient to such an extent that code 2 will be more efficient for Memory (and CPU?): Saving the variable a inside the loop makes it a Gen0, so this will be garbage collection before variable b .
Thus, when used with the garbage collection language, code 2 is more efficient. I'm right?
source share