Is there a performance difference between cascading if-else statements like
if (i > 0) {
// ...
} else if (i > 1) {
// ...
} else if (i > 2) {
// ...
} else if (i > 3) {
// ...
} else if (i > 4) {
// ...
} else if (i > 5) {
// ...
} else if (i > 6) {
// ...
} else if (i > 7) {
// ...
} else if (i > 8) {
// ...
} else if (i > 9) {
// ...
} else if (i > 10) {
// ...
} else if (i > 11) {
// ...
} else if (i > 12) {
// ...
} else if (i > 13) {
// ...
} else if (i > 14) {
// ...
} else if (i > 15) {
// ...
} else if (i > 16) {
// ...
} else if (i > 17) {
// ...
} else if (i > 18) {
// ...
} else if (i > 19) {
// ...
} else if (i > 20) {
// ...
}
and nested if statements like:
if (i > 10) {
if (i > 15) {
if (i > 18) {
if (i > 19) {
if (i > 20) {
// ...
} else {
// ...
}
} else {
//...
}
} else {
if (i > 17) {
// ...
} else {
// ...
}
}
} else {
if (i > 13) {
if (i > 14) {
// ...
} else {
// ...
}
} else {
if (i > 12) {
// ...
} else {
// ...
}
}
}
} else {
if (i > 5) {
if (i > 8) {
if (i > 9) {
//...
} else {
//...
}
} else {
if (i > 7) {
// ...
} else {
// ...
}
}
} else {
if (i > 3) {
if (i > 4) {
// ...
} else {
// ...
}
} else {
if (i > 2) {
// ...
} else {
if (i > 1) {
// ...
}
}
}
}
}
If there is a difference what is the reason one is faster than the other? I am particularly interested in the performance in Java but would be interested in knowing who it might be similar or different in other languages like C/C++, C#, etc.
How would different distributions of i and/or a different number of if statements effect the results?
Aucun commentaire:
Enregistrer un commentaire