-1

I just wanted to know in general, is this code inefficient:

for (int i = 0; i < array.size(); i++) {
    //do something
}

as opposed to:

int x = array.size(); 

for (int i = 0; i < x; i++) {
    //do something
}

or is it negligible? (How about in nested for loops?)

user2665166
  • 441
  • 4
  • 8
  • 17

4 Answers4

3

Assuming array is an ArrayList, it's of almost no difference since the implementation of size() merely accesses a member field:

public int size() {
    return size;
}

The second code just saves the field value in a local variable and re-uses it in the loop instead of accessing the field every time, so that's just a difference between an access to a local variable versus an access to a field (accessing a local variable is slightly faster).

M A
  • 71,713
  • 13
  • 134
  • 174
1

You can test it yourself doing some test like below:

public static void main(String[] args) {
    ArrayList<Long> array = new ArrayList<Long>(99999);
    int i = 0;
    while (i < 99999) {
        array.add(1L);
        i++;
    }
    long ini1 = System.currentTimeMillis();
    i = 0;
    for (int j = 0; j < array.size(); j++) {
        i += array.get(j);
    }
    long end1 = System.currentTimeMillis();
    System.out.println("Time1: " + (end1 - ini1));
    long ini2 = System.currentTimeMillis();
    i = 0;
    for (int j = 0; j < 99999; j++) {
        i += array.get(j);
    }
    long end2 = System.currentTimeMillis();
    System.out.println("Time2: " + (end2 - ini2));
}

Output:

Time1: 13
Time2: 10

I think that the difference its irrelevant in most applications and cases, i run the test several times and the times vary but the difference keeps "constant" at least in terms of percentage...

melli-182
  • 1,216
  • 3
  • 16
  • 29
  • 1
    I think that the second loop should use a local variable not the literal `99999` in order to exactly replicate the OP's case. But that should not really make a difference... – M A Aug 26 '15 at 20:12
  • @manouti yeah, you are right, but i test both cases and the result are pretty similar, i choose this to reduce some code ;). – melli-182 Aug 26 '15 at 20:13
0

Arrays don't have a size, but length

for (int i = 0; i < array.length; i++) {
    //do something
}

Efficiency is O(1).

0

actually, performance is almost the same if array.size is not very big. u can always make like this:

for (int i = 0, x = array.length; i < x; i++) {
    //do something
}