dimanche 24 janvier 2021

Which combination of switch and if/else is faster and why?

I have two sets of conditions. One has two possible values and the other has more (in this example I wrote 3 cases but there could be up to 8). Which code runs faster and is less error prompt (more accurate)?

code a)

if (letter.equals(a)) {
  switch (number) {

    case 1:
           .........
    case 2:
           .........
    case 3:
           .........
  }
} else if (letter.equals(b)) {
  switch (number) {

    case 1:
           .........
    case 2:
           .........
    case 3:
           .........
  }
}

code b)

switch (number) {

    case 1:

           if (letter.equals(a)) {
              .........
           } else if (letter.equals(b)) {
              .........
           }

    case 2:

           if (letter.equals(a)) {
              .........
           } else if (letter.equals(b)) {
              .........
           }

    case 3:

           if (letter.equals(a)) {
              .........
           } else if (letter.equals(b)) {
              .........
           }
  }

Please tell me if you think there is a better option other than these two. (I could also create a parameter that gets both letter and number and create 6 cases using that.)

Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire