mardi 19 avril 2016

Efficiency "if" vs "for"

I have got the following question. Suppose I have an array of values. Let it be an array of ints for simplicity int arr[n]. n is a finite arbitrary number. The idea is to check if some consecutive elements of the array are the same. One way to do it is to use a (large) condition in "if":

...
int val = arr[i];
if (arr[i-2] == val && arr[i-1] == val && ...) {
  // Equal
} else {
  // not equal
}
...

where i is some "midpoint" element around which the check should be done.

The other option to do this is to use the "for" (or some other) loop:

...
int val = arr[i];
bool eq = true;
for (int j=i-2;j<i+2;++j){
  if (arr[j] != val){
    eq = false;
    break;
  }
}
if (eq) {
  // Equal
} else {
  // Not equal
}
...

It seems that the first solution is more efficient as it does not require extra data structures and checks, but more error-prone and less scalable. On the other hand, the second solution is more generic and flexible, but requires more checks (and perhaps memory).

Question 1: Which solution is more efficient from the execution perspective (e.g., performance)?

Question 2: How does the efficiency depend on the data structure of the array (e.g., if it is a complex structure) and the compiler?

Question 3: Does the efficiency depend on language (e.g., Java vs C)?

Aucun commentaire:

Enregistrer un commentaire