TypedArrays, ArrayBuffer, and Zero-Copy Transfers vs Web Crypto API and SubtleCrypto
TypedArrays transfer raw buffers to workers for custom math, whereas crypto.subtle processes ArrayBuffers natively off-thread.
Structured Comparison Matrix
| Dimension | TypedArrays, ArrayBuffer, and Zero-Copy Transfers | Web Crypto API and SubtleCrypto |
|---|---|---|
| Mental Model | Contiguous binary buffers (ArrayBuffer) paired with unboxed numeric views (Uint8Array, Float32Array) that transfer across workers in O(1) via ownership handoff. | Native C++-backed cryptographic primitives (AES-GCM, SHA-256, ECDSA, HKDF) running off the JS thread in secure contexts with non-extractable CryptoKey handles. |
| Maturity & Domain | Baseline · Widely · JS Runtime Chrome 7+ · Firefox 4+ · Safari 5.1+ | Baseline · Widely · Web APIs Chrome 37+ · Firefox 34+ · Safari 11+ |
| Prerequisites | ||
| When Not to Use | When not to use TypedArray: Avoid TypedArray for small, sparse, or mixed-type lists, creating a backing ArrayBuffer costs more than a small literal [1, 2, 3]; for hashing or encryption over binary buffers, pass the ArrayBuffer directly to Web Crypto (SubtleCrypto). | When not to use SubtleCrypto: Never roll custom client-side password hashing to replace server-side Argon2id or TLS transport security. |
Engine Mechanics & Trade-Offs
ArrayBuffer allocates a raw contiguous byte block while TypedArray views index it directly without JS object boxing, enabling O(1) transfer between workers.
Key Pitfalls: Host Endianness Trap: Uint32Array reads bytes in host CPU order (little-endian on x86/ARM), silently scrambling big-endian network headers. Use-After-Transfer Crash: Reading a TypedArray after transferring its ArrayBuffer throws TypeError or returns empty slices.
SubtleCrypto dispatches cryptographic operations off the JS thread to the browser's native C++ crypto library and isolates raw key bytes behind opaque CryptoKey handles.
Key Pitfalls: Reusing an AES-GCM IV: Encrypting two messages with the same key and 12-byte iv destroys confidentiality and authentication; always call crypto.getRandomValues(new Uint8Array(12)) per message. Missing window.isSecureContext: crypto.subtle is undefined on plain http:// staging URLs; test over HTTPS or localhost.