3

Do Dart unnecessary package imports have any performance drawback?

Let's say I wanted to export a set of files for convenience, but whenever I import those files I won't use everything inside of them. In this case, is there any performance drawback for unnecessary files?

goodonion
  • 1,401
  • 13
  • 25
  • 1
    Well, I would guess the Dart parser are going through all the files but this is just a one time performance cost (which are also really small). But hereafter, no, there are no runtime performance cost for including code which are never called. – julemand101 Sep 09 '20 at 11:20

2 Answers2

4

Maybe.

Dart will spend time parsing the extra libraries at compile-time.

If you are lucky, the compiler will recognize that none of the imported classes or functions are used, and "tree-shake" away them before compiling the rest. If you are really unlucky, it won't detect that (maybe you are using dart:mirrors, so you might access the declarations through that). If you are really not using any part of that library, then there is a very good chance that tree-shaking will work.

When compiling code ahead-of-time (for example for the web), if the unused code is not tree-shaken away, it will affect the size of your program. Download time is also performance, especially on the web, so that is an effect. It might also affect some optimizations.

For example, if the compiler knows that there is only one method in the program called flamboozle, then it might optimize the invocation of o.flamboozle() to a direct call instead of a virtual interface call. If your extra library also contains a flamboozle method, and it wasn't detected that the library won't be used, then that optimization might not be used. So, extra code can affect performance, even if it's not used, as long as it's not obvious that it's not used.

In most cases, I wouldn't worry about performance for an imported and completely unused library. The code that you do use is a more likely reason for performance issues. The readability and risk-of-name-conflict issues are bigger, so I'd still remove the import.

lrn
  • 64,680
  • 7
  • 105
  • 121
1

Unused imports have no performance impact at runtime. Nonetheless, you should always import only what you need for readability and avoid namespace collisions which are a nuisance.

Does unused import and objects have a performance impact

Hamed
  • 5,867
  • 4
  • 32
  • 56