0Pricing
WebAssembly (WASM) for High Performance Apps · Aula

Expandindo e gerenciando a memória linear

Aprenda como a memória linear do WASM cresce sob demanda, como dimensioná-la e como gerenciar alocações com segurança a partir do JavaScript e do módulo.

Expandindo e gerenciando a memória linear é uma aula grátis de WebAssembly (WASM) for High Performance Apps no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de WebAssembly (WASM) for High Performance Apps, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de WebAssembly (WASM) for High Performance Apps inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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 page

Buffers 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 page

Allocators 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/_free carve the space
  • Free what you allocate; size initial/max thoughtfully

Careful memory management keeps high-performance WASM apps fast and leak-free.

Perguntas Frequentes

A aula “Expandindo e gerenciando a memória linear” é grátis?

Sim — o texto completo de “Expandindo e gerenciando a memória linear” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de WebAssembly (WASM) for High Performance Apps, atualize para CoddyKit PRO. O curso de WebAssembly (WASM) for High Performance Apps inclui 4 aulas no total.

O que vou aprender em “Expandindo e gerenciando a memória linear”?

Aprenda como a memória linear do WASM cresce sob demanda, como dimensioná-la e como gerenciar alocações com segurança a partir do JavaScript e do módulo. Você pratica WebAssembly (WASM) for High Performance Apps com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar WebAssembly (WASM) for High Performance Apps?

Nenhuma experiência prévia é necessária. WebAssembly (WASM) for High Performance Apps no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Expandindo e gerenciando a memória linear”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de WebAssembly (WASM) for High Performance Apps?

Sim. Cada aula de WebAssembly (WASM) for High Performance Apps inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Passando estruturas de dados complexas
  2. Modelo e gerenciamento de memória do WASM
  3. Memória compartilhada e atômicos
  4. Expandindo e gerenciando a memória linear
← Voltar para WebAssembly (WASM) for High Performance Apps