0

I was wondering which one is better in term of memory allocation. I know at this scale these would not be any different since creating a variable would take so little memory, but I wanted to get used to coding the better way for the future.

public static void test(Scanner input, int[] arr){
    for (int i = 0; i < 5; i++){
        int age = input.nextInt();
        arr[i] = age;
    }

or

public static void test(Scanner input, int[] arr){
    int age = null;
    for (int i = 0; i < 5; i++){
        age = input.nextInt();
        arr[i] = age;
    }
}

Declaring the variable before the for loop would only allocate one place in memory for all the values I set it to, correct? But if I declare the variable in the for loop, will 5 different places in memory be allocated or just one that will be overwritten when the for loop is run again?

I should also state that the variable age will not be used anywhere else but inside that for loop.

Thanks.

Arc676
  • 4,445
  • 3
  • 28
  • 44
Mauricio
  • 3
  • 1
  • 2
    Look at this thread: http://stackoverflow.com/questions/407255/difference-between-declaring-variables-before-or-in-loop – Matt Dec 06 '15 at 11:06

6 Answers6

1

Shouldn't make any difference, so my suggestion is limit it to the required scope (i.e. option 1) - also int age = null; is a bit misleading - makes you read like it's a pointer even though it isn't. int age = 0; would be a bit clearer.

John3136
  • 28,809
  • 4
  • 51
  • 69
1

many discussion: already there: Difference between declaring variables before or in loop?

There are others factors: static, global.

In general, the more performance, the less readable, the less safe

Community
  • 1
  • 1
0

The difference in performance, if not eliminated by the compiler's optimization, would not be noticeable at all. What is noticeable, and should be taken into account, is the readability of your code.

Declaring the variable before the loop only makes the code harder to read, and also pollutes the namespace outside the loop. As a general rule of thumb, declare your variables in the smallest scope where you need them.

Joffrey
  • 32,348
  • 6
  • 68
  • 100
0

Which is better, first or second?

From a performance perspective, you'd have to measure it. (And in my opinion, if you can measure a difference, the compiler isn't very good).

From a maintenance perspective, first is better. Declare and initialize variables in the same place, in the narrowest scope possible. Don't leave a gaping hole between the declaration and the initialization, and don't pollute namespaces you don't need to.

Abdelhak
  • 8,299
  • 4
  • 22
  • 36
0

Don't use temporary variable yourself, this one is better:

public static void test(Scanner input, int[] arr){
for (int i = 0; i < 5; i++){
    arr[i] = input.nextInt();
}

}

Mohammad
  • 55
  • 1
  • 9
0

If variable will be used only within cycle, then declare it within cycle, in order to pollute function's namespace.