Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "import * as" less efficient than specific named imports? [duplicate]

Suppose I have a module foo like this:

export const f = x => x + 1;

export const g = x => x * 2;

I can use this module like this:

import { f, g } from 'foo';

console.log(f(g(2)));

Or like this:

import * as foo from 'foo';

console.log(foo.f(foo.g(2)));

I prefer the second way because it prevents name collisions between modules.

However, is import * less efficient? Does it prevent bundlers (such as Rollup and Webpack) from spotting unused imports and removing them?

like image 500
sdgfsdh Avatar asked Mar 21 '18 22:03

sdgfsdh


2 Answers

When you specify imports as import { f, g } from 'foo'; you guarantee better performance in terms of speed in compilation and bundle size as you will be getting only the dependencies you need.

Notes: as loganfsmyth pointed out, some recent compiler/bundle are able to reference what actually is being used only, this IMO is an additional step which could cost some compilation time (although I did not have time to benchmark this assumption).

like image 71
GibboK Avatar answered Oct 18 '22 21:10

GibboK


import * is less efficient in that you are using more memory to pull the entire library as opposed to just the specific methods that you actually need

like image 1
Jacob Kaddoura Avatar answered Oct 18 '22 23:10

Jacob Kaddoura