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.
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.
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.