Do function names affect performance?
Swift is a precompiled language, and all objects are converted to memory addresses; however, there is a special "Selector" in Swift that allows functions to be found by function names at runtime. How did this work? Does this mean that naming functions will affect operational efficiency?
No, function names do not meaningfully affect performance in Swift.
Function and method names are used in two primary ways once compiled into your program:
- When a function is called directly (statically) by name, the compiled code refers to the symbol (function name, converted into a format suitable for inclusion in the binary code produced) — which is then converted into a constant jump operation during linking, either statically or dynamically
- Simplified: the function name has no effect on calling the function; it is not taken into consideration in any way when making the call
- When a function is called dynamically using the Objective-C runtime (e.g., as a selector), the function name is used to look up the appropriate method in a class's method cache. Selectors are unique in a program, so function/method names are mapped to a globally-unique selector, which is then what is used for lookup (by pointer, not by name)
- When you refer to a selector statically (e.g. with
#selector(...)
), the unique selector is pre-compiled in to your program, so the name never needs to be looked up at runtime, and the selector pointer itself can instead be used directly when calling methods - If you refer to a selector dynamically (e.g.
NSSelectorFromString(...)
), the selector is looked up from the given name dynamically (in a global table of unique selectors), and if not found, a new selector is dynamically created at runtime
- When you refer to a selector statically (e.g. with
In both case (1) and (2a), the name of the function is never really used in the process of making the call, and is irrelevant. In case (2b), it technically is (for selector lookup), but the process is so fast that it really doesn't matter. Method names are rarely long, since they are most often typed by hand, and compared to most operations a program can perform, even the most dynamic use-case (looking up methods manually at runtime) is so insignificant that you really shouldn't worry about it.
One other consideration: when you compile a program with symbols embedded in it, those symbols take up space in your binary. You shouldn't really worry about that either because:
- A release build of a program will have most symbols stripped out, and
- Compared to the size of a binary due to code, the amount of space symbols take up is usually also totally insignificant