I have a contract, in which I maintain the keys of a mapping in two different ways:

  1. Storing each key in an array
  2. Emitting an event for each key

I do this in order to be able to restore the keys (and subsequently the values) of the mapping whenever needed.

My questions are:

  1. Which method is considered cheaper?
  2. Which method allows restoring the keys faster?

Intuitively, I feel that the answer to question #2 is 'the array', which then leads me to believe that the answer to question #1 is 'the events' (otherwise why would anyone ever use them?). Am I correct?

A 3rd question is - will I be able to reconstruct the keys without either one of these solutions, e.g., by downloading the entire block-chain and then scanning it thoroughly?

Here is a minimized version of my contract:

pragma solidity 0.4.25;

contract DataBase {
    struct Record {
        bool valid;
        uint index;

    mapping(address => Record) public table;

    address[] public array;

    event Added(address indexed key);
    event Removed(address indexed key);

    function add(address key) external {
        require(key != address(0));
        Record storage record = table[key];
        record.valid = true;
        record.index = array.length;
        emit Added(key);

    function remove(address key) external {
        Record storage record = table[key];
        require(array.length > record.index);
        require(key == array[record.index]);
        address last = array[array.length - 1];
        table[last].index = record.index;
        array[record.index] = last;
        array.length -= 1;
        delete table[key];
        emit Removed(key);

Thank you!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.