mardi 27 septembre 2016

Swift Micro optimization: multiple if statements where fall-though will not occur vs if else if

If there is a difference which of these techniques is results in faster execution and why?

Using if statements allows calculating numberOnePlusOne only once.

func test(numberOne:Int, numberTwo:Int) {
    if numberOne == numberTwo {
      return
    }
    let numberOnePlusOne = numberOne + 1
    if numberOnePlusOne == numberTwo && numberOnePlusOne < numberTwo {
      return
    } else {
      return
    }
}

So if Using if else if is beneficial I would assume the benefit would be from the telling the compiler the blocks can't fall-though without an operation.

func test(numberOne:Int, numberTwo:Int) {
    if numberOne == numberTwo {
      return
    } else if numberOne + 1 == numberTwo && numberOne + 1 < numberTwo {
      return
    } else {
      return
    }
}

Aucun commentaire:

Enregistrer un commentaire