mardi 28 avril 2015

Java: if, switch or question mark double point

Which of the following methods is the fastest?

int i;
String s;

1. If Else

if(i == 0)
    s = "Case A"
else if(i == 1)
    s = "Case B"
else
    s = "Case C"

2. Switch

switch(i) {
    case 0:
        s = "Case A"; break;
    case 1:
        s = "Case B"; break;
    default:
        s = "Case C"; break;
}

3. ? and :

s = (i == 0 ? "Case A" : (i == 1 ? "Case B" : "Case C"))

Also, are method 1 and 3 compiled with the same output?

Aucun commentaire:

Enregistrer un commentaire