Why does changing a storage slot's value from zero to non-zero cost more than changing from non-zero to non-zero, zero to zero, or non-zero to zero?
By default, all storage locations have zero value on the EVM. So when you change a slot from zero to non-zero, the overall size of the state increases. This means, all the nodes have to allocate extra storage to accommodate for the new slot you created. However, when you change a non-zero to another non-zero, it doesn't increase the overall size of the EVM state. That storage slow was already occupying some space and it's just rewritten. Hence the difference in gas used.
Additionally, some gas is refunded when you delete some variable, when the
SELFDESTRUCT opcode is executed, as it frees up storage. Read more