The question is pertinent yes if the code block in if contains high computational complexity, written in the database or in files, etc..
The ideal between the two would be the (A).
Why Performance(A) >= Performance(B)
Case 1: the implementation of the programme has always exibirAdeus = true
, Performance(A) = Performance(B). Both (A) and (B) will end up having the same flow:
Algorithm (A), Algorithm (B):
1. Atribui "" ou "Oi" para `message`
2. Verifica `exibirAdeus == true`
3. Atribui "Adeus" para `message`
Case 2: the implementation of the programme has 1 or more exibirAdeus = false
, Performance(A) > Performance(B). Because for such cases (B) will be more costly:
Algorithm (A):
1. Atribui "Oi" para `message`
2. Verifica `exibirAdeus == true`: falso, não faz nada (message já é "Oi"). continua adiante.
Algorithm (B):
1. Atribui "" para `message`
2. Verifica `exibirAdeus == true`: falso, precisa atribuir "Oi".
3. Atribui "Oi" para `message`
Real World
However, if this block is small and of low complexity, it becomes extremely unnecessary.
The path you would follow is: How readable and easy to maintain this code (readability & maintainability). I say this because there is a consensus* that in this case presented, you should be more concerned with placing the keys ({}) to demarcate the blocks of the if-Else.
string mensagem = "OI"; // padrão: caso mais provável...
if (exibirAdeus) {
mensagem = "Adeus";
}
or, if the code starts to become more complicated as remembered by C. E. Gesser:
private bool Teste(){
[..]
string mensagem = initMensagem(condicao);
[..]
}
private string initMensagem(bool condicao){
if (condicao) {
return "Adeus";
}
return "OI";
}
Another common case
string message = "";
if (condicao == 1){
message = "blablbla";
}
else if (condicao == 2){
message = "Lorem";
}
else if (condicao == 3){
message = "Ipsum";
}
[..]
else {
message = "Dolor";
}
This would be better written** for performance, readability and maintainability:
string message = "";
switch (condicao) {
case 1:
message = "blablbla";
break;
case 2:
message = "Lorem";
break;
case 3:
message = "Ipsum";
break;
[..]
default:
message = "Dolor";
}
*
https://softwareengineering.stackexchange.com/questions/16528
https://softwareengineering.stackexchange.com/questions/2715
https://stackoverflow.com/questions/15786949
**
https://stackoverflow.com/questions/445067
https://stackoverflow.com/questions/767821
https://stackoverflow.com/questions/395618
A) does not necessarily perform better than B). The correct performance would be equal or better.
– Andre Figueiredo
I was curious to know why there was a negative vote here. I wanted to learn where the problem of the answer is.
– Maniero