TextEncoder: Converting Strings to Uint8Array for WebSockets and More

Day 86 of me reading random and basic but important dev topicsss.... After text decoder I read about text encoder..... Yesterday, I read about how TextDecoder turns raw binary bytes into readable strings. But what happens when we need to send a string over a WebSocket, hash it with the Web Crypto API, or write it to a low-level file stream? We have to do the reverse: Convert the String into a Uint8Array of bytes. For this, we use TextEncoder. Unlike TextDecoder which supports various encodings, TextEncoder is strictly standardized to support only UTF-8. This ensures cross-platform consistency for modern web applications. let encoder = new TextEncoder(); let uint8Array = encoder.encode("Hello"); console.log(uint8Array); // Uint8Array(5) [72, 101, 108, 108, 111] 1. The encodeInto() Optimization: The standard .encode(str) method creates a brand new Uint8Array every time it's called. If you are encoding strings inside a tight loop (e.g. a game engine or a high-throughput data parser), allocating new memory repeatedly will trigger the Garbage Collector and cause performance spikes. Instead, use encodeInto(str, destination). This method takes your string and writes the bytes directly into an existing Uint8Array buffer that you have already allocated. let encoder = new TextEncoder(); let preAllocatedBuffer = new Uint8Array(256); // Allocate memory once // Encode directly into the existing buffer let result = encoder.encodeInto("Hello", preAllocatedBuffer); console.log(result.read); // 5 (characters read) console.log(result.written); // 5 (bytes written into the buffer) This zero-allocation technique is a massive win for high-performance applications! Understanding ArrayBuffer, Uint8Array, TextDecoder, and TextEncoder gives you full control over how memory and data flow through your JavaScript applications. Keep Learning!!!! #JavaScript #Nodejs #FrontendDevelopment #WebSockets #WebAssembly #CodingTips

  • graphical user interface

To view or add a comment, sign in

Explore content categories