mercredi 27 octobre 2021

Redundant assignment vs check before assignment in Java

In front of a long loop, it costs more (processor + memory) to assign redundantly the same value, or to check before the assignment? 

int count = 0;
for(int i=0; i<100_000; i++){
    if (...) {
        count++
        doLogic(count); // logic is strictly related with count
    } else {
      count = 0;  //50.000 redundant assignment
    }
}

VS.

int count = 0;
for(int i=0; i<10_000; i++){
    if (...) {
        count++
        doLogic(count); // logic is strictly related with count
    } else {
        if(count > 0) { // 50.000 checks 
          count = 0;
        }
    }
}

And would it cost the same if count would be present in a different object (injected as singleton in a spring context) and the increments/check/reset would be like:

config.incrementCount();
config.getCount();
config.resetCount();

Aucun commentaire:

Enregistrer un commentaire