The question is pertinent 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 (A).
Why Performance (A) > = Performance (B)
Case 1 : Program execution always has exibirAdeus = true
, Performance (A) = Performance (B) . Both (A) and (B), will always 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 : Program execution has 1 or more exibirAdeus = false
, Performance (A) > Performance (B) . Because for these 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, this becomes extremely unnecessary.
The path you would follow is: How easy this code is for readability (readability & maintainability). I say this because there is a consensus * that in this case presented, you should be more concerned with putting the braces ({}) to demarcate the if-else blocks.
string mensagem = "OI"; // padrão: caso mais provável...
if (exibirAdeus) {
mensagem = "Adeus";
}
or if the code starts to get more complicated as reminded 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";
}
It 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";
}
* link
link link
**
link
link