Results 1 to 3 of 3
  1. #1
    rp181 is offline Member
    Join Date
    Mar 2009
    Posts
    70
    Rep Power
    0

    Default 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;
    ...
    }
    }
    XML Code:
    int z;
    for(int i = 0; i < 100; i++){
    for(int d = 0; d < 200; d++){
    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?

  2. #2
    iluxa is offline Senior Member
    Join Date
    Mar 2010
    Posts
    266
    Rep Power
    5

    Default

    Depends on Java version and operating system, but I've seen declaration of variable outside the loop help performance in some configurations.

  3. #3
    paul pasciak is offline Senior Member
    Join Date
    Jul 2008
    Posts
    125
    Rep Power
    0

    Default 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'.

    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);
    */
      }
    }
    Otherwise, you raise a valid question.
    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

  1. need some help with loops!
    By Chewart in forum New To Java
    Replies: 2
    Last Post: 12-04-2009, 12:32 AM
  2. when should we use loops
    By shahemaan in forum New To Java
    Replies: 1
    Last Post: 10-31-2009, 02:38 AM
  3. While Loops, need a bit of help.
    By Keno777 in forum New To Java
    Replies: 7
    Last Post: 10-30-2009, 09:24 PM
  4. how to use do while loops
    By mikeitalydz in forum New To Java
    Replies: 32
    Last Post: 09-26-2009, 09:30 PM
  5. Loops (while do etc)
    By manupr in forum New To Java
    Replies: 1
    Last Post: 01-15-2008, 04:59 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •