Do import statements in Swift have an associated cost?

前端 未结 2 970
眼角桃花
眼角桃花 2021-02-20 11:53

Reading the String Manifesto, I saw a paragraph about avoiding the Foundation import when not necessary.

Why is this a concern to the Swift team? Apart from

2条回答
  •  隐瞒了意图╮
    2021-02-20 12:29

    While there is no doubt that importing frameworks increases the raw file size of your app, they are generally very well compressed. And if you need the framework, you have no choice but to import it. Practically, however, file size is not an issue when it comes to frameworks--relatively large ones, like Mapbox, can be included at the cost of just a few MB to your end product. And it's a shared cost by all apps so it's a wash.

    Framework code is also stored in shared libraries, not in your executable, which is a very important distinction. Regardless of which Apple platform you're programming for, read Apple's OS X documentation on frameworks because the general concepts are the same. In it, it briefly talks about the relationship between framework inclusion and performance:

    If you are worried that including a master header file may cause your program to bloat, don’t worry. Because OS X interfaces are implemented using frameworks, the code for those interfaces resides in a dynamic shared library and not in your executable. In addition, only the code used by your program is ever loaded into memory at runtime, so your in-memory footprint similarly stays small.

    As for including a large number of header files during compilation, once again, don’t worry. Xcode provides a precompiled header facility to speed up compile times. By compiling all the framework headers at once, there is no need to recompile the headers unless you add a new framework. In the meantime, you can use any interface from the included frameworks with little or no performance penalty.

    https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPFrameworks/Tasks/IncludingFrameworks.html

    That said, don't import frameworks that are already imported by default from "umbrella" frameworks. For example, importing UIKit automatically imports Foundation so don't import both. Does this really make a difference? No, but caring about the details, even the unimportant ones, is what will snowball someone into a programmer other people want to hire and work with. I can't tell you how many programmers I've collaborated with in the past who had the "who cares" attitude about things like this. It's no surprise their code was always the sloppiest and they're the ones always out of work.

提交回复
热议问题