tags:

views:

126

answers:

7

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;
+3  A: 

No.

  • In Class1 the variable a is a field, accessible by all methods in the class.
  • In Class2 this is not the case: a is a local variable within the method assign. After assign finishes, the value of a is discarded.
Stephan202
+2  A: 

No, one has an instance variable a (Class1), and one has not.

Bart Kiers
+4  A: 

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.

Jon Skeet
+5  A: 
  • Yes. Both of them are totally useless.
  • No. Instance size of Class1 is greater than instance size of Class2, due to the member variable.

The answer depends on what you mean by saying "equal" =)

SadSido
+1 for mentioning the senselessness of it all.
Bombe
A: 

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.

andy
A: 

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.

M1EK
A: 

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.

Jesper