Skip to content

Improve chunking algorithm for dynamic imports to recognize already loaded modules - #3305

Closed
tjenkinson wants to merge 48 commits into
rollup:masterfrom
tjenkinson:improve-chunking-algo-dynamic-imports
Closed

tjenkinson wants to merge 48 commits into
rollup:masterfrom
tjenkinson:improve-chunking-algo-dynamic-imports

Conversation

@tjenkinson

@tjenkinson tjenkinson commented Dec 25, 2019 •

Copy link
Copy Markdown
Member

This PR contains:

  • bugfix
  • feature
  • refactor
  • documentation
  • other

Are tests included?

  • yes (bugfixes and features will not be merged without tests)
  • no

Breaking Changes?

  • yes (breaking changes will not be merged unless absolutely necessary)
  • no

List any relevant issue numbers:

Description

This updates chunkColouring so that when a module is imported, if it is already assigned a colour, and something in the import tree also has that colour, it will remain unchanged, because it means the module will already be in memory.

@lukastaegert
lukastaegert self-requested a review December 28, 2019 09:10
@codecov

codecov Bot commented Dec 31, 2019 •

Copy link
Copy Markdown

Codecov Report

Merging #3305 into master will increase coverage by 0.01%.
The diff coverage is 89.39%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #3305      +/-   ##
==========================================
+ Coverage   93.18%   93.19%   +0.01%     
==========================================
  Files         172      172              
  Lines        6059     6068       +9     
  Branches     1804     1807       +3     
==========================================
+ Hits         5646     5655       +9     
  Misses        220      220              
  Partials      193      193
Impacted Files Coverage Δ
src/utils/collapseSourcemaps.ts 90% <0%> (ø) ⬆️
src/utils/defaultPlugin.ts 94% <0%> (ø) ⬆️
src/ast/nodes/TaggedTemplateExpression.ts 63.63% <0%> (ø) ⬆️
src/utils/FileEmitter.ts 100% <100%> (ø) ⬆️
src/ast/nodes/Identifier.ts 100% <100%> (ø) ⬆️
src/utils/chunkColouring.ts 94.64% <100%> (ø) ⬆️
src/ast/nodes/MemberExpression.ts 98.27% <100%> (ø) ⬆️
src/utils/transform.ts 95% <100%> (ø) ⬆️
src/ast/nodes/CallExpression.ts 95.41% <100%> (ø) ⬆️
src/finalisers/umd.ts 94.91% <100%> (ø) ⬆️
... and 10 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 529a9a8...a0ed839. Read the comment docs.

…e dynamic module instead

because the dynamic chunk now contains the contents of 'main-static.js'
@lukastaegert
lukastaegert force-pushed the improve-chunking-algo-dynamic-imports branch from 11bef6e to 55ca332 Compare January 10, 2020 16:15

@lukastaegert lukastaegert left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, I know this is still WIP. I started adding some of the basic test cases specific to dynamic imports to see what it actually does. One issue is that when there are multiple entry points importing a dynamic chunk, the algorithm generates too few chunks and leads to code that is executed that should not have been executed. I did not yet look into the algorithm, just some early feedback.

import { value } from './main.js';
export { value } from './main.js';

console.log('dynamic', value);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks how it should for the simple case: The dynamic chunk is importing its value from main.js and we avoided the shared chunk. 👍

import { v as value2 } from './generated-dep2.js';
export { v as value2 } from './generated-dep2.js';

console.log('dynamic1', value1, value2);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this scenario, we have two entry points that both dynamically import a single module. The imported module shares two dependencies with one entry point and only one with the other.

Unfortunately, this is broken: dep1 should not have been inlined into main1 because now if the user starts executing the code from the other entry point main2, main1 will also be loaded by the dynamic module. This was not the case before bundling.

Instead, all modules need to become separate chunks

  • dep1 cannot be inlined into main1 or main2 because it is shared
  • dep2 cannot be inlined into main1 because it is not guaranteed to be in memory when the dynamic chunk is loaded

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 got it thanks for the simpler test. will take a look

@tjenkinson

Copy link
Copy Markdown
Member Author

Started working on a slightly different approach

@tjenkinson

Copy link
Copy Markdown
Member Author

@lukastaegert thanks for your solution. There's some tidying to do and the new tests need proper names/descriptions (so not marking it ready for review yet), but I think the solution I have is working. I spent some time looking at the fixture changes with both yours and mine

There are quite a few fixture changes I need to spend some more time checking. Also still a few other test failures

Some points:

  • with your solution manual-chunks-dynamic-facades changes, but with mine it remains the same as master
  • the event ordering tests seem to have changed with both solutions. I think the failures are identical so might be ok
  • I haven't tested the performance difference between both solutions. I don't mind which one ends up being used. It's been a good challenge working on this :)

@lukastaegert

Copy link
Copy Markdown
Member

with your solution manual-chunks-dynamic-facades changes, but with mine it remains the same as master

This looks indeed broken in my setup, thanks for checking!

the event ordering tests seem to have changed with both solutions

What do you mean by "event ordering"?

I haven't tested the performance difference between both solutions. I don't mind which one ends up being used. It's been a good challenge working on this :)

Let's have a look once everything is in place and see which is picked. In the end, I will also learn something from yours and it is good to have more than algorithm available when it comes to integrating future improvements.

@lukastaegert

Copy link
Copy Markdown
Member

with your solution manual-chunks-dynamic-facades changes, but with mine it remains the same as master

Indeed there was a check missing for a manualChunkAlias in the loop for dynamic entries that was present in the loop for static entries. I updated the code in the post above to fix it, nicely spotted!

@tjenkinson

Copy link
Copy Markdown
Member Author

What do you mean by "event ordering"?

I meant the emit-chunk-order tests

I updated all the tests so that the build is green and tidied up the implementation, but need to check they make sense.

Both my implementation and yours though pass all the tests in this PR, so it's nice to know functionally they're the same :)

@tjenkinson tjenkinson changed the title [WIP] Improve chunking algorithm for dynamic imports to recognize already loaded modules Improve chunking algorithm for dynamic imports to recognize already loaded modules Jan 18, 2020
@tjenkinson
tjenkinson marked this pull request as ready for review January 18, 2020 21:38

@lukastaegert lukastaegert left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry this is taking a while, this is quite a bit to work through. Your implementation is now passing all my simple test cases as well except for a non-trivial one that I added to your PR. I think this would be nice to get right. The situation is when

  • we have two entry points that share two dependencies (without a dynamic chunk, this would create three chunks, one for each entry point and one for the two dependencies)
  • both entry points contain a dynamic import that only depends on one of the shared dependencies

As the this dependency is already in memory, there is no reason to create another chunk for it, however your algorithm splits the shared chunk.

I added the _expected folder created by my alternative algorithm.

@lukastaegert
lukastaegert force-pushed the improve-chunking-algo-dynamic-imports branch from bd5fdc3 to b19ef0d Compare January 22, 2020 07:14
@lukastaegert

lukastaegert commented Jan 23, 2020 •

Copy link
Copy Markdown
Member

Unfortunately, performance is indeed a bigger problem. I created a small rollup-config.js that simulates a non-trivial setup with lots of static and dynamic imports via virtual modules:

const FILES = 1000;
const ENTRIES = 5;
const DYNAMIC_ENTRIES = 10;
const DYNAMIC_IMPORTS_PER_FILE = 2;
const STATIC_IMPORTS_PER_FILE = 20;

function getFileName(idx) {
  return `file_${idx}`
}

function getRandomFile(start, end) {
  return getFileName(start + Math.floor(Math.random() * (end - start)))
}

export default {
  input: [...Array(ENTRIES).keys()].map(getFileName),
  plugins: [
    {
      resolveId(id) {
        return id;
      },
      load(id) {
        const idx = Number(id.slice(5));
        let output = `console.log("${id}");`;
        for (let idx = 0; idx < STATIC_IMPORTS_PER_FILE; idx++) {
          output += `import "${getRandomFile(ENTRIES + DYNAMIC_ENTRIES, FILES)}";`;
        }
        for (let idx = 0; idx < DYNAMIC_IMPORTS_PER_FILE; idx++) {
          output += `import("${getRandomFile(ENTRIES, ENTRIES + DYNAMIC_ENTRIES)}");`;
        }
        return output;
      }
    }
  ],
  output: [
    {
      dir: 'dist',
      format: 'esm'
    }
  ]
};

When I run this script with npx rollup -c --perf and look at the timings for ## generate chunks: ... I get

  • for the original algorithm: 40 - 60ms
  • for my algorithm: 70 - 100ms
  • for your algorithm it does not seem to complete at all

As a matter of fact when I turn down FILES as low as 30, I still get runs with your algorithm of up to 80 seconds. I think the idea of your algorithm is good but it does not cache information in a necessary way which I think gives it a performance order of (number_of_files)^2 (this is just a rough estimate) while my algorithm has (number_of_entries) * (number_of_files), which converges better as there is usually only a small amount of entry points.

@tjenkinson

Copy link
Copy Markdown
Member Author

Thanks for the extra test and performance script. I see where the issue is and would be interested in adding some caching now there’s a nice way to measure the speed

@tjenkinson

tjenkinson commented Jan 25, 2020 •

Copy link
Copy Markdown
Member Author

Rewrote it a bit and it handles the new test case. Still need to check performance now.

Also first use of optional chaining :)

if (!module.manualChunkAlias && importer?.manualChunkAlias) {
	module.manualChunkAlias = importer.manualChunkAlias;
}

@lukastaegert

Copy link
Copy Markdown
Member

Nice, and you are doing great work! Still, I know you have already put a lot of effort in this, but we could also just release the other algorithm for now? The thing is, I would like to have this released soon before 2.0.0 is ready (which will be another 3 or so weeks, but still), and I need this as an argument to finally remove experimentalOptimizeChunks from Rollup.

@tjenkinson

tjenkinson commented Jan 25, 2020 via email •

Copy link
Copy Markdown
Member Author

…modules

if there are now more loaded modules than before there's no point processing, given not painting the loaded modules would have no effect given they were already painted in the previous run
@tjenkinson
tjenkinson force-pushed the improve-chunking-algo-dynamic-imports branch from cafeb4a to a0ed839 Compare January 26, 2020 12:19
@lukastaegert

Copy link
Copy Markdown
Member

This has been superseded by the currently published version of Rollup

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants