Optimizations in if-else statements

I'm wondering if there are different performance characteristics in the following examples:

// 1
if x ~= a {
    return b
}
return c

// 2
if x ~= a {
    return b
} else {
    return c
}

// 3
switch x {
case a:
    return b

default:
    return c
}

Thanks!

I wouldn't expect there to be.

A good way to evaluate that, since it's a very small snippet, is to examine the compiled binary (i.e. with godbolt) and check if they differ at all

Interestingly, this code is so similar that if you put them in three different functions it will create the first one and have the other two delegate to that one: Compiler Explorer

(As an aside, does the Swift compiler have an equivalent for -fomit-frame-pointer?)

1 Like

i thought llvm handled all the rbp stuff

i thought switch statements got compiled to jump tables? or does swift know to reduce the 2 case version to an if-else

Sure, but I can't figure out how to pass the correct flags to it from the swiftc frontend.

How switches and ifs get lowered is generally up to llvm. It can canonicalize either form to the other, depending on what its heuristics guess is best. For equivalent control flow, in theory you should end up with the same output, and like @saagarjha observed, the identical implementations can then be folded into one function.