1

What should one use to update the values, mutate or insert? And why in algorithm point of view?

<SimpleMap<T>>::insert(&user, entry);
<SimpleMap<T>>::mutate(&user, |entry_option| {
                         *entry_option = Some(entry);
            });

2 Answers 2

3

Insert is just for inserting or overwriting any existing value. If you just want to put a specific value into storage, then use that.

Mutate is meant for cases where you want to modify the existing value or want to do some other case-decision depending on the current value.

For example when you want to increment a value, it can be written shorter with mutate:

let v = match MyInt::<T>::get() {
    // Calculate new value
};
MyInt::<T>::set(&v);

// But it is shorter with mutate
MyInt::<T>::mutate(|v| match v {
    // Calculate and set new value
}
4

Insert will do just a write to the database.

Mutate will do a read and a write, which is significantly more expensive, as any database operation is expensive.

So in the cases where you COULD use insert (not needing the read the value), you should use insert over mutate.

Your Answer

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

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