Skip to content

Commit e1e892d

Browse files
committed
perf(led-ring): speed up
avoid costy querySelectorAll() in `setPixel()` by caching the result
1 parent 510563d commit e1e892d

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

src/led-ring-element.ts

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { customElement, html, LitElement, property, queryAll, svg } from 'lit-element';
1+
import { customElement, html, LitElement, property, svg } from 'lit-element';
22
import { ElementPin } from './pin';
33
import { RGB } from './types/rgb';
44

@@ -29,7 +29,7 @@ export class LEDRingElement extends LitElement {
2929
*/
3030
@property() animation = false;
3131

32-
@queryAll('.pixel') pixelElements: SVGCircleElement[] = [];
32+
private pixelElements: SVGCircleElement[] | null = null;
3333

3434
private animationFrame: number | null = null;
3535

@@ -58,8 +58,22 @@ export class LEDRingElement extends LitElement {
5858
];
5959
}
6060

61+
private getPixelElements() {
62+
if (!this.shadowRoot) {
63+
return null;
64+
}
65+
if (!this.pixelElements) {
66+
this.pixelElements = Array.from(this.shadowRoot.querySelectorAll('rect.pixel'));
67+
}
68+
return this.pixelElements;
69+
}
70+
6171
setPixel(pixel: number, { r, g, b }: RGB) {
62-
const { pixelElements } = this;
72+
const pixelElements = this.getPixelElements();
73+
if (!pixelElements) {
74+
return;
75+
}
76+
6377
if (pixel < 0 || pixel >= pixelElements.length) {
6478
return;
6579
}
@@ -70,7 +84,8 @@ export class LEDRingElement extends LitElement {
7084
* Resets all the pixels to off state (r=0, g=0, b=0).
7185
*/
7286
reset() {
73-
for (const element of this.pixelElements) {
87+
const pixelElements = this.getPixelElements();
88+
for (const element of pixelElements ?? []) {
7489
element.style.fill = '';
7590
}
7691
}
@@ -118,6 +133,8 @@ export class LEDRingElement extends LitElement {
118133
transform="rotate(${angle} ${radius} ${radius})"/>`
119134
);
120135
}
136+
this.pixelElements = null; // Invalidate element cache
137+
121138
return html`
122139
<svg
123140
width="${width}mm"

0 commit comments

Comments
 (0)