1

I'd like to know if it costs more to access several times a value at array[i] or to stock the value as a new variable (v=array[i]) and access the variable v several times instead ?

for example (in java), would it be better to write :

int [] array = {1,2,3,4,5};

for(int i=0;i<5;i++){
    if (array[i]<0){
        System.out.println("negativ");
    }else if(array[i]>0){
        System.out.println("positiv");
        if (array[i]==42){
            System.out.println("great answer");
        }
    }else{
        System.out.println("zero");
    }
}

or

int [] array = {1,2,3,4,5};
int v;

for(int i=0;i<5;i++){
    v = array[i];
    if (v<0){
        System.out.println("negativ");
    }else if(v>0){
        System.out.println("positiv");
        if (v==42){
            System.out.println("great answer");
        }
    }else{
        System.out.println("zero");
    }
}

Thank you for your help.

Mireille
  • 11
  • 3

4 Answers4

1

You end up taking two more bytes with the second form:

  34: istore_2
  35: iload_2

Variable access ends up being an iaload vs an iload_2 - not a huge difference. If you had enough variables (more than 4) that you had to use iload (index) rather than iload_ then you would see even larger code for the second form.

To be explicit: you don't save anything by introducing the variable, and in fact add instructions (where the variable gets set).

user3486184
  • 2,147
  • 3
  • 26
  • 28
0

Both the styles have their pros and cons
For array[i] access it might be little cumbersome to read but is a safer bet. In your example you are only reading from the array, think of a case where you have to write as well. You might end up updating just v and that might prove to be a quite costly bug !!

Another point to note is your example is about primitive array hence the storage/access overhead I guess is pretty negligible

Zakir
  • 2,222
  • 21
  • 31
  • Thank you very much for your answers, this has been very helpful :-) – Mireille Jun 13 '17 at 04:54
  • Glad that it helped you - would you mind accepting/up voting it - might help others reaching here with the same question – Zakir Jun 13 '17 at 16:58
  • I tried to up vote it but I don't have enough of reputation for my votes to be counted yet (sorry). I'll come back once I'll get some :-) – Mireille Jun 13 '17 at 21:15
0

Neither. The java language has the enhanced for loops optimization for this:

int [] array = {1,2,3,4,5};

for(int v: array){
    if (v<0){
        System.out.println("negativ");
    }else if(v>0){
        System.out.println("positiv");
        if (v==42){
            System.out.println("great answer");
        }
    }else{
        System.out.println("zero");
    }
}
K.Nicholas
  • 10,956
  • 4
  • 46
  • 66
0

The JVM will optimize both to the same thing so it makes no difference. Prefer the most readable.

user207421
  • 305,947
  • 44
  • 307
  • 483