[StimulusBundle] Stop watching the DOM once every lazy controller is loaded - #3783
Open
Kocal wants to merge 1 commit into
Open
[StimulusBundle] Stop watching the DOM once every lazy controller is loaded#3783Kocal wants to merge 1 commit into
Kocal wants to merge 1 commit into
Conversation
Contributor
📊 Packages dist files size differenceThanks for the PR! Here is the difference in size of the packages dist files between the base branch and the PR.
|
|||||||||
Kocal
force-pushed
the
perf/stimulus-bundle-lazy-observer
branch
2 times, most recently
from
August 15, 2026 22:21
046f3cc to
8b9797f
Compare
…loaded
| Q | A
| -------------- | ---
| Bug fix? | no
| New feature? | no
| Deprecations? | no
| Documentation? | no
| Issues | -
| License | MIT
The `MutationObserver` installed for lazy controllers kept running for the
lifetime of the page. Every `childList` mutation triggered a
`querySelectorAll('[data-controller]')` over the mutated subtree, even
after all lazy controllers had already been requested and nothing could
match anymore.
Disconnect the observer as soon as the lazy controller map is empty. On
Turbo or Live Component pages, which mutate the DOM constantly, this
removes the repeated subtree scans entirely.
300 DOM mutations on a 500-row page, after the last lazy controller has
been loaded: **~530 ms -> ~81 ms** (means of 3 runs, jsdom via Vitest).
Browser-side JavaScript, so there is no Blackfire profile for this one.
Measured by loading the only lazy controller, then churning the DOM the
way a Turbo page does, with this throwaway test in
`src/StimulusBundle/assets`:
```ts
import { Application, Controller } from '@hotwired/stimulus';
import { describe, expect, it } from 'vitest';
import { loadControllers } from '../../dist/loader';
import type { LazyControllersCollection } from '../../src/controllers';
describe('loader cost after every lazy controller is loaded', () => {
it('measures repeated DOM mutations', async () => {
const page = document.createElement('div');
page.innerHTML = Array.from(
{ length: 500 },
(_, i) => `<div class="row"><span data-x="${i}">row ${i}</span><button>go</button></div>`
).join('');
document.body.appendChild(page);
const application = Application.start();
const lazyControllers: LazyControllersCollection = {
lazy1: () => Promise.resolve({ default: class extends Controller {} }),
};
loadControllers(application, {}, lazyControllers);
// Load the only lazy controller, so nothing is left to look for.
const trigger = document.createElement('div');
trigger.setAttribute('data-controller', 'lazy1');
document.body.appendChild(trigger);
await new Promise((resolve) => setTimeout(resolve, 20));
expect(Object.keys(lazyControllers)).toHaveLength(0);
const start = performance.now();
for (let i = 0; i < 300; i++) {
const node = document.createElement('div');
node.innerHTML = `<p>update ${i}</p>`;
page.appendChild(node);
page.removeChild(node);
}
await new Promise((resolve) => setTimeout(resolve, 50));
console.log(`300 mutations -> ${(performance.now() - start).toFixed(2)} ms`);
application.stop();
});
});
```
The behaviour itself is covered by a permanent unit test asserting the
observer is disconnected once the last lazy controller has been loaded:
```bash
pnpm exec vitest --run test/unit/loader.test.ts
```
Analysis, implementation and benchmarks by Claude Opus 5.
Kocal
force-pushed
the
perf/stimulus-bundle-lazy-observer
branch
from
August 15, 2026 22:56
8b9797f to
97b7713
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The
MutationObserverinstalled for lazy controllers kept running for the lifetime of the page. EverychildListmutation triggered aquerySelectorAll('[data-controller]')over the mutated subtree, even after all lazy controllers had already been requested and nothing could match anymore.Disconnect the observer as soon as the lazy controller map is empty. On Turbo or Live Component pages, which mutate the DOM constantly, this removes the repeated subtree scans entirely.
300 DOM mutations on a 500-row page, after the last lazy controller has been loaded: ~530 ms -> ~81 ms (means of 3 runs, jsdom via Vitest).
Browser-side JavaScript, so there is no Blackfire profile for this one. Measured by loading the only lazy controller, then churning the DOM the way a Turbo page does, with this throwaway test in
src/StimulusBundle/assets:The behaviour itself is covered by a permanent unit test asserting the observer is disconnected once the last lazy controller has been loaded:
pnpm exec vitest --run test/unit/loader.test.tsAnalysis, implementation and benchmarks by Claude Opus 5.