Is using an ES6 import to load specific names faster than importing a namespace?

TL;DR: It does not matter.


import * as … from 'ramda';
import { … } from 'ramda';

will both by default always bring in the complete Ramda module with all its dependencies. All code inside the module would be run, and which syntax was used to reference the exported bindings doesn’t matter. Whether you use named or namespaced imports comes down to preference entirely.

What can reduce the file size to download and the used memory is static analysis. After having evaluated the module, the engine can garbage-collect those bindings that are referenced from nowhere. Module namespace objects might make this slightly harder, as anyone with access to the object can access all exports. But still those objects are specified in a way (as immutable) to allow static analysis on their usage and if the only thing you’re doing with them is property access with constant names, engines are expected to utilise this fact.

Any size optimisation involves guessing which parts of the module need to be evaluated and which not, and happens in your module bundler (like Rollup or WebPack). This is known as Tree Shaking, dropping parts of the code and entire dependencies when not needed (used by anything that got imported). It should be able to detect which imports you are using regardless of the import style, although it might have to bail out when are doing unusual things with the namespace object (like looping it or using dynamic property access).

To learn about the exact guesses your bundler can make, contact its documentation.

Leave a Comment