javascript / expert
Snippet
Bit-Gepackter Typisierter Array-Speicher für Zustands-Knoten-Ablaufsteuerung
Dieses Muster nutzt binäre Uint32Array-Puffer, um Booleansche Zustands-Knoten in 32-Bit-Ganzzahlelemente innerhalb von React-Komponenten zu packen. Bitweise XOR- und AND-Operationen ermöglichen O(1)-Zustandsumschaltungen und -Abfragen bei minimalem Speicherverbrauch.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import React, { useMemo, useState } from 'react';export function BitPackedNodeGraph({ nodeCount = 1024 }) {const [, setRevision] = useState(0);const nodeBuffer = useMemo(() => {const buffer = new Uint32Array(Math.ceil(nodeCount / 32));for (let i = 0; i < buffer.length; i++) {buffer[i] = (1 << (i % 32)) | (1 << ((i + 3) % 32));}return buffer;}, [nodeCount]);const toggleNode = (index) => {const wordIndex = Math.floor(index / 32);const bitMask = 1 << (index % 32);nodeBuffer[wordIndex] ^= bitMask;setRevision((prev) => prev + 1);};return (<button onClick={() => toggleNode(5)}>Bit 5 Status: {(nodeBuffer[0] & (1 << 5)) !== 0 ? 'Active' : 'Inactive'}</button>);}
react
Erklärung
1
const buffer = new Uint32Array(Math.ceil(nodeCount / 32));
Allokiert einen zusammenhängenden Speicherblock, der 32 binäre Zustands-Knoten pro Array-Eintrag speichert.
2
nodeBuffer[wordIndex] ^= bitMask;
Schaltet den Bit-Zustand des Zielknotens über bitweises XOR ohne neue Objektallokation um.