6

I'm using a Vec<T> in ink!. When allocating elements to the vec, the underlying array may be resized to provide a constant amortised push complexity of O(1). This means that sometimes the vec has unused space (e.g. 5 items in the vec but the underlying array has length 8 with 3 null elements).

Does the vec get stored with or without the unused space in the smart contract?

I am currently considering calling shrink_to_fit() before saving the vec in smart contract storage in order to save space. However, I'm hoping ink! does this automatically.

1 Answer 1

4

Values written to the contract storage in ink! are SCALE encoded. That means that no matter the capacity of the vector, the encoded value only includes what is in the vec.

Consider this:

When

let mut vec1 = Vec::new();
for _ in 0..5 {
   vec1.push(1);
}

let mut vec2 = Vec::new();
for _ in 0..5 {
   vec2.push(1);
}
vec2.shrink_to_fit();

Then

assert_eq!(vec1.encode(), vec2.encode())

Also when

let mut vec1 = Vec::with_capacity(10);
vec1.push(10);

let vec2 = vec![10];

Then

assert_eq!(vec1.encode(), vec2.encode());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.