Hi, local variables that you need in a block, do you declare them at the top of the block, or when you need them ?? do you do long test; for (int i=0;i<whatEver;i++)> { test = ... } or do you do for (int i=0;i<whatEver;i++)> { long test = ... }
I know the above one is more efficient, but the below one produced more readable code... No problem if you only use one var, but there are alot of vars I use sometimes What's your opinion ??
for the following simple reason. In the first case, the risk is to forget to remove the variable declaration if ever you remove the loop. Moreover, I do not like scrolling back and forth to see what the variable name or type exactly was. W.
In C, you had to declare your stuff at the top of the function and initialize it later. In Java, the rule of thumb is to not declare something until you have to.
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
I understand declaring everything as local as possible, but if you declare something within a loop are you not slowing things down - for no real good reason?
Please ignore post, I have no idea what I am talking about.
Dave Van Even
Ranch Hand
Joined: Jul 19, 2001
Posts: 101
posted
0
That is what I was also thinking!! It's also possible that alot of objects will gave to be created while in a loop.
Wilfried LAURENT
Ranch Hand
Joined: Jul 13, 2001
Posts: 269
posted
0
You are right. The loops (while, for, do) may not be good examples for local variable declarations inside the block they are used. But I think it can be applied for other block types (if-then, try-catch ...). W.
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
10
posted
0
>It's also possible that alot of objects will gave to be created while in a loop.
An int is not an object. The question changes if you are declaring objects within the loop.
Have you tried timing it both ways? I suggest that you loop a billion times with the int declared in the loop and again with the int declared outside the loop, and see if it makes a difference. [This message has been edited by Marilyn deQueiroz (edited October 12, 2001).]
An int is not an object. The question changes if you are declaring objects within the loop.
Good point. So I did as you suggested and the results came out opposite of what I thought they schould be. Doing everything inside of the loop is actually faster, for an int and an object. Let me know if did something wrong here. Here are the results: Test #1 took: 2312 // int outside of loop Test #2 took: 2158 // int inside of loop Test #3 took: 34 // object outside of loop Test #4 took: 0 // object inside of loop Dummy object:
Test driver:
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.