Results 1 to 3 of 3
Thread: Variable Management in Loops
- 03-23-2010, 10:21 PM #1
Member
- Join Date
- Mar 2009
- Posts
- 70
- Rep Power
- 0
Variable Management in Loops
Which is better, if any are better?
Java Code:for(int i = 0; i < 100; i++){ for(int d = 0; d < 200; d++){ int z = i*d; ... } }This is a totally random example. Does "recreating" the variable everytime actually have an effect? Or should you declare changing variables beforehand?XML Code:int z; for(int i = 0; i < 100; i++){ for(int d = 0; d < 200; d++){ z = i*d; ... } }
- 03-23-2010, 10:23 PM #2
Senior Member
- Join Date
- Mar 2010
- Posts
- 266
- Rep Power
- 4
Depends on Java version and operating system, but I've seen declaration of variable outside the loop help performance in some configurations.
- 03-23-2010, 11:20 PM #3
Senior Member
- Join Date
- Jul 2008
- Posts
- 125
- Rep Power
- 0
Here is z answer..
Your two code snippets are somewhat different from each other.
They might not be use to perform the same task.
Both of them are below.
One will not compile (I did this to emphasize the difference)
because the variable is out of 'scope'.
Otherwise, you raise a valid question.Java Code:class TryZ{ public static void main(String[] args){ int z=0; for(int i = 0; i < 100; i++){ for(int d = 0; d < 200; d++){ z = i*d; } } System.out.println(z); /* for(int i = 0; i < 100; i++){ for(int d = 0; d < 200; d++){ int zz = i*d; } } System.out.println(zz); */ } }
I have read in one book that:
Java Code:int length = array.length; for(int i=0; i<length; i++){ ; }
is faster than
Java Code:for(int i=0; i<array.length; i++){ ; }
Similar Threads
-
need some help with loops!
By Chewart in forum New To JavaReplies: 2Last Post: 12-03-2009, 11:32 PM -
when should we use loops
By shahemaan in forum New To JavaReplies: 1Last Post: 10-31-2009, 01:38 AM -
While Loops, need a bit of help.
By Keno777 in forum New To JavaReplies: 7Last Post: 10-30-2009, 08:24 PM -
how to use do while loops
By mikeitalydz in forum New To JavaReplies: 32Last Post: 09-26-2009, 08:30 PM -
Loops (while do etc)
By manupr in forum New To JavaReplies: 1Last Post: 01-15-2008, 03:59 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks