Aumentar y gestionar la memoria lineal
Aprenda cómo crece bajo demanda la memoria lineal de WASM, cómo dimensionarla y cómo gestionar las asignaciones de forma segura desde JavaScript y el módulo.
Aumentar y gestionar la memoria lineal es una lección gratuita de WebAssembly (WASM) for High Performance Apps en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de WebAssembly (WASM) for High Performance Apps, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de WebAssembly (WASM) for High Performance Apps incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
One Big Array
WASM stores all its data in a single, contiguous block called linear memory, exposed to JS as a growable ArrayBuffer.
Understanding how it grows and how to manage it is key to high-performance modules.
Memory Is Page-Based
Linear memory is measured in pages of 64 KiB each.
- 1 page = 65536 bytes
- Memory grows in whole pages, never partial
Declaring Initial and Max Size
When creating memory you set an initial and optional maximum number of pages.
const memory = new WebAssembly.Memory({
initial: 2, // 128 KiB
maximum: 100 // up to ~6.4 MiB
});Growing Memory
Call grow(n) to add n pages. It returns the previous size, or throws if it would exceed the maximum.
const prevPages = memory.grow(1); // add one 64 KiB pageBuffers Become Detached
Important: growing memory detaches the old ArrayBuffer. Any typed-array view you held is now invalid, re-create it after growth.
memory.grow(1);
// old view is stale; make a fresh one
const view = new Uint8Array(memory.buffer);Growing From Inside WASM
WASM code grows its own memory with the memory.grow instruction; allocators like Rust's do this automatically when the heap fills.
(memory.grow (i32.const 1)) ;; grow by 1 pageAllocators on Top of Memory
Languages provide an allocator (malloc, Rust's global allocator) that carves the linear memory into objects.
You rarely manage raw offsets, you let the allocator and bindings do it.
Allocating From JS
Emscripten exposes _malloc and _free so JS can reserve space in WASM memory for data to pass in.
const ptr = Module._malloc(1024);
// ... use the buffer at ptr ...
Module._free(ptr);Avoiding Leaks
Memory you allocate must be freed, WASM has no garbage collector for its linear memory. Forgetting free leaks until the module is discarded.
Sizing Strategy
Tune memory for your workload:
- Start with enough initial pages to avoid early growth
- Set a maximum to cap runaway usage
- Remember each grow detaches views, batch growth when possible
Best Practices Summary
To manage linear memory well:
- Think in 64 KiB pages
- Re-create views after every
grow - Pair every alloc with a free
- Pick sensible initial and maximum sizes
Quick Check
What must you do immediately after calling memory.grow()?
Recap
You learned to manage WASM linear memory:
- Memory grows in 64 KiB pages via
grow() - Growth detaches buffers, refresh your views
- Allocators and
_malloc/_freecarve the space - Free what you allocate; size initial/max thoughtfully
Careful memory management keeps high-performance WASM apps fast and leak-free.
Preguntas frecuentes
¿La lección «Aumentar y gestionar la memoria lineal» es gratis?
Sí — el texto completo de «Aumentar y gestionar la memoria lineal» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de WebAssembly (WASM) for High Performance Apps, actualiza a CoddyKit PRO. El curso de WebAssembly (WASM) for High Performance Apps incluye 4 lecciones en total.
¿Qué aprenderé en «Aumentar y gestionar la memoria lineal»?
Aprenda cómo crece bajo demanda la memoria lineal de WASM, cómo dimensionarla y cómo gestionar las asignaciones de forma segura desde JavaScript y el módulo. Practicas WebAssembly (WASM) for High Performance Apps con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar WebAssembly (WASM) for High Performance Apps?
No se requiere experiencia previa. WebAssembly (WASM) for High Performance Apps en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Aumentar y gestionar la memoria lineal»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de WebAssembly (WASM) for High Performance Apps?
Sí. Cada lección de WebAssembly (WASM) for High Performance Apps incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Pasar estructuras de datos complejas
- Modelo y gestión de memoria de WASM
- Memoria compartida y atómicos
- Aumentar y gestionar la memoria lineal