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;
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.