Skip to content

Instantly share code, notes, and snippets.

@nikkaroraa
Created May 19, 2022 18:22
Show Gist options
  • Save nikkaroraa/314eff49d21329f8a56a7b8c3d3e71a4 to your computer and use it in GitHub Desktop.
Save nikkaroraa/314eff49d21329f8a56a7b8c3d3e71a4 to your computer and use it in GitHub Desktop.
zero copy account on solana - via anchor

Zero-copy

Zero-copy is a deserialization technique that creates data structures by borrowing (not copying!) from the array holding the input, avoiding the expensive memory allocation and processing of traditional deserialization. With zero-copy, we can create accounts larger than the size of the stack or heap.

Usage

To enable zero-copy-deserialization, one can pass in the zero_copy argument to the macro as follows:

#[account(zero_copy)]

This can be used to conveniently implement ZeroCopy so that the account can be used with AccountLoader.

Other than being more efficient, the most salient benefit this provides is the ability to define account types larger than the max stack or heap size. When using borsh, the account has to be copied and deserialized into a new data structure and thus is constrained by stack and heap limits imposed by the BPF VM. With zero copy deserialization, all bytes from the account’s backing RefCell<&mut [u8]> are simply re-interpreted as a reference to the data structure. No allocations or copies necessary. Hence the ability to get around stack and heap limitations.

AccountLoader

Account AccountLoader facilitating on demand zero copy deserialization.

Note that using accounts in this way is distinctly different from using, for example, the ProgramAccount. Namely, one must call load, load_mut, or load_init, before reading or writing to the account.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment