Cost of empty inline function?

205 Views Asked by At

I'm writing a debugging function that will be called from other function in my project. This function is marked as @inline(__always), and does nothing if DEBUG is 0.

Does this function have any cost whatsoever at DEBUG == 0? I'm pretty sure that the answer is no, but I just want to confirm it.

1

There are 1 best solutions below

0
On

tl;dr

Zero cost


Elaboration

I'm assuming your function looks something like this:

@inline(__always)
func myFunction() {
    #if DEBUG
    doStuff()
    doStuff()
    doStuff()
    #endif
}

First, the preprocessor directives are followed. So if your DEBUG flag is 0, you can think of it as being preprocessed into this:

@inline(__always)
func myFunction() {
}

When you call myFunction anywhere, it's replaced with its contents at compile time. Assuming DEBUG is still 0, can think of it like this:

// What you wrote:
func myOtherFunction() {
    print("Before")
    myFunction()
    print("After")
}

// Imagine it becoming this while compiling:
func myOtherFunction() {
    print("Before")
    print("After")
}

And, as you can see, the non-content of your inlined empty function are included, introducing zero cost to calling this function in this compilation environment.

Obviously, Swift code is not compiled into more Swift code. That's why I said you can imagine this; it's not truly what's happening. In actuality, it gets compiled into LLVM IR, but the end result is the same.