nalo
nalo

Reputation: 1018

Quick question about primitives

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;

Upvotes: 0

Views: 206

Answers (7)

Jesper
Jesper

Reputation: 206796

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.

Upvotes: 0

M1EK
M1EK

Reputation: 820

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.

Upvotes: 0

andy
andy

Reputation: 1

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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500225

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.

Upvotes: 4

SadSido
SadSido

Reputation: 2551

  • 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" =)

Upvotes: 5

Bart Kiers
Bart Kiers

Reputation: 170148

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

Upvotes: 2

Stephan202
Stephan202

Reputation: 61499

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.

Upvotes: 3

Related Questions