Does adding extensions to primitive types like Int decrease overall app performance?

Just curious; say I wanted to add some extensions like Int.random(), will that affect the runtime performance of my program in any way, wherever Int is used, even when those extensions were not called?

It might effect your compile time but not your runtime. For extension Int { func random() { ... } } the compiler generates something close to:

extension Int {
    static func random(x: Int) { ... } // IE a static func in the namespace Int

Then when you type x.random() the compiler generates:


So just syntax sugar.


One thing to keep in mind here is that the generated code will stick around in compiled binary even if you don’t call it; e.g. Int.random() will be embedded in the file and make it larger. If that’s something that matters to you, I’d suggest against adding a lot of extensions that you never use.

Why can’t the Swift compiler optimize away unused extensions?

It will if you use WMO mode, and even without that the linker probably will do it too if you don’t mark them public. But the compiler has to be very, very sure you’re not using it…which includes dynamic use. (Specifically, if you make a type conform to a protocol, the compiler has to assume you might want to test if it conforms to that protocol somewhere else in the program, and can’t eliminate anything that it needs for that conformance. Similarly, an “unused” @objc function can still be called from outside the Swift world.)