Skip to content

Commit

Permalink
fix(grid): plug a mememory leak from the render process
Browse files Browse the repository at this point in the history
  • Loading branch information
Westbrook committed Oct 14, 2023
1 parent 23d7b50 commit f0c3d7b
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 2 deletions.
7 changes: 6 additions & 1 deletion tools/grid/src/Grid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
PropertyValues,
ReactiveElement,
render,
RootPart,
TemplateResult,
} from '@spectrum-web-components/base';
import { property } from '@spectrum-web-components/base/src/decorators.js';
Expand All @@ -35,6 +36,8 @@ export class Grid extends LitVirtualizer {
return [styles];
}

private __gridPart: RootPart | undefined = undefined;

@property({ type: String })
public focusableSelector!: string;

Expand Down Expand Up @@ -147,20 +150,22 @@ export class Grid extends LitVirtualizer {
}

if (this.isConnected) {
render(super.render(), this);
this.__gridPart = render(super.render(), this);
}
super.update(changes);
}

override connectedCallback(): void {
super.connectedCallback();
this.__gridPart?.setConnected(true);
this.addEventListener('change', this.handleChange, { capture: true });
}

override disconnectedCallback(): void {
this.removeEventListener('change', this.handleChange, {
capture: true,
});
this.__gridPart?.setConnected(false);
super.disconnectedCallback();
}
}
72 changes: 72 additions & 0 deletions tools/grid/test/grid-memory.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
Copyright 2023 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

import { expect, fixture, nextFrame } from '@open-wc/testing';
import { html, render } from '@spectrum-web-components/base';
import { Default } from '../stories/grid.stories';

async function usedHeapMB(): Promise<number> {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const memorySample = performance.measureUserAgentSpecificMemory();
return (await memorySample).bytes / (1024 * 1024);
}

describe('Grid memory usage', () => {
it('releases references on disconnect', async function () {
if (!window.gc || !('measureUserAgentSpecificMemory' in performance))
this.skip();

this.timeout(10000);

const iterations = 50;
let active = false;

const el = await fixture<HTMLElement>(
html`
<div></div>
`
);

async function toggle(
forced: boolean | undefined = undefined
): Promise<void> {
active = forced != null ? forced : !active;
render(active ? Default() : html``, el);
await nextFrame();
await nextFrame();
}

// "shake things out" to get a good first reading
for (let i = 0; i < 5; i++) {
await toggle();
}
await toggle(false);
const beforeMB = await usedHeapMB();

for (let i = 0; i < iterations; i++) {
await toggle();
}
await toggle(false);
const afterMB = await usedHeapMB();

/**
* An actually leak here shapes up to be more than 10MB per test,
* we could be more linient later, if needed, but the test currently
* shows less heap after the test cycle.
*/
expect(
afterMB - beforeMB,
`before: ${beforeMB}, after: ${afterMB}`
).to.be.lt(0);
});
});
10 changes: 9 additions & 1 deletion web-test-runner.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { sendMousePlugin } from './test/plugins/send-mouse-plugin.js';
import {
chromium,
chromiumWithFlags,
chromiumWithMemoryTooling,
configuredVisualRegressionPlugin,
firefox,
packages,
Expand Down Expand Up @@ -54,6 +55,13 @@ export default {
}
},
},
{
name: 'measureUserAgentSpecificMemory-plugin',
transform(context) {
context.set('Cross-Origin-Opener-Policy', 'same-origin');
context.set('Cross-Origin-Embedder-Policy', 'credentialless');
},
},
],
mimeTypes: {
'**/*.json': 'js',
Expand Down Expand Up @@ -135,5 +143,5 @@ export default {
},
],
group: 'unit',
browsers: [chromium, firefox, webkit],
browsers: [chromiumWithMemoryTooling, firefox, webkit],
};
22 changes: 22 additions & 0 deletions web-test-runner.utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,28 @@ export const chromium = playwrightLauncher({
}),
});

export const chromiumWithMemoryTooling = playwrightLauncher({
product: 'chromium',
createBrowserContext: ({ browser }) =>
browser.newContext({
ignoreHTTPSErrors: true,
permissions: ['clipboard-read', 'clipboard-write'],
}),
launchOptions: {
headless: false,
args: [
'--js-flags=--expose-gc',
'--headless=new',
/**
* Cause `measureUserAgentSpecificMemory()` to GC immediately,
* instead of up to 20s later:
* https://web.dev/articles/monitor-total-page-memory-usage#local_testing
**/
'--enable-blink-features=ForceEagerMeasureMemory',
],
},
});

export const chromiumWithFlags = playwrightLauncher({
product: 'chromium',
launchOptions: {
Expand Down

0 comments on commit f0c3d7b

Please sign in to comment.