Edited this question because of my bad examples.. Here is my updated question:
Would the following be equal in speed and memory allocation:
int b;
for (int i = 0; i < 1000; i++)
b = i;
and
for (int i = 0; i < 1000; i++)
int b = i;
Edited this question because of my bad examples.. Here is my updated question:
Would the following be equal in speed and memory allocation:
int b;
for (int i = 0; i < 1000; i++)
b = i;
and
for (int i = 0; i < 1000; i++)
int b = i;
No.
Class1
the variable a
is a field, accessible by all methods in the class.Class2
this is not the case: a
is a local variable within the method assign
. After assign
finishes, the value of a
is discarded. No, it wouldn't.
In the first case you've got one variable being assigned 1000 different values - and you end up being able to get hold of the last value (999) after the constructor has completed.
In the second case you're calling an essentially no-op method 1000 times. The second method has no side-effects and has no return value, so it's useless. The local variable only "exists" for the duration of the method call, whereas the instance variable in the first example is part of the object, so will live on.
Note that this isn't restricted to primitives - any other type would behave the same way too.
The answer depends on what you mean by saying "equal" =)
In the first instance you've already declared b as an int and its value is updated each time the loop executes. In the second, b is declared and initialized to the value of i each time the loop executes. I'm not 100% sure but I think that the second case is more memory intensive but I don't think that the speed difference would be noticeable.
It's worth noting that any compiler worth its salt, and I firmly believe the JIT to be worth lots of salt, would just set aside space for "b" ONCE in the second case, i.e. the 'declaration' phase would be meaningless.
Have you tried this out? It doesn't even compile!
for (int i = 0; i < 1000; i++)
int b = i;
Error messages from the compiler:
Example.java:4: '.class' expected
int b = i;
^
Example.java:4: not a statement
int b = i;
^
Example.java:4: illegal start of expression
int b = i;
^
The body of a loop must contain at least one statement. A variable declaration is not a statement, so a loop with just a variable declaration is invalid.